React state和props使用场景

一个组件的显示状态能够由内部状态state、外部参数props所决定。javascript

props:java

  一、props 是从外部传进组件的参数,主要是父组件向子组件传递数据。服务器

  二、props 对于使用它的组件来讲是只读的。要想修改props,必须经过父组件修改。因此子组件的props 一般是父组件的state。this

  三、默认值spa

    为了组件的健壮性,在传入props 的时候常给默认值。对象

const SubComponent=(props)=> {
  return (<h1>{props.name}</h1>)
}
SubComponent.defaultProps = {
  name: 'Rain_tdk'
};
export default SubComponent

  四、为开发方便咱们须要对props 的数据类型进行检验blog

import PropTypes from 'prop-types';
const SubComponent=(props)=> {
  return (<h1>{props.name}</h1>)
}
SubComponent.defaultProps = {
  name: 'Rain_tdk'
};
SubComponent.propTypes = {
  name: PropTypes.string
};
export default SubComponent

  更多检验参考 :https://www.jianshu.com/p/2896acb5746b事件

state:ip

  一、state是React组件中的私有对象,用于控制这个组件自己的状态开发

  二、setState()采用merge的方式修改state。setState会从新调用render()刷新UI,直接经过this.state=‘xxx’的方式也会修改state可是不会从新渲染。

   注:setState({...newState})当state为Object、Arrary 时diff 比较的是引用,不会刷新UI 。须要使用 concat /slice /...运算符等产生新引用的方法。

  三、应用场景:

      大部分组件的工做应该是从props里取数并渲染出来,可是当须要 用户输入、服务器请求、延定时变化 等做出响应。

      一般在有状态state的组件中处理用户交互逻辑,并经过props传递给子组件(一般为无状态组件)中。

  四、那些属性应该用state

      state 中应该保存可能被事件处理器改变并触发用户页面更新的数据。

  五、哪些属性不该该存储在state中

      5-一、计算所得数据。计算数据应该在render()中实现,若是存储在state中须要手动更新state 比较麻烦

      5-二、基于props 的重复数据。组件中应该保持props为惟一的数据来源,除非须要知道历史数据是啥。

      5-三、不要将React组件保存在state中。在render()里使用props、state来建立他。

  总结:state让你修改(不修改的数据别往state存)。props不让你修改。多个state、props共同影响UI 的时在render()中实现。

相关文章
相关标签/搜索