zoukankan      html  css  js  c++  java
  • props设置state误区

    class Component extends React.Component {
      constructor(props) {
        super(props);
        this.state = { value: this.props.value };
      }
      
      render() {
        return <div>The value is: {this.state.value}</div>
      }
    }

    如上代码所示,仅仅在constructor中将props赋值给state,constructor仅在组件创建时执行一次,props发生变化不会执行,因此,render中的value仅显示初始值,不会发生变化

    如下,在constructor和componentWillReceiveProps都进行props的赋值,才可以完美解决props设置state的问题:

    class Component extends React.Component {
      constructor(props) {
        super(props);
        this.state = { value: this.props.value };
      }
      componentWillReceiveProps(nextProps) {
        if(nextProps.value !== this.props.value) {
          this.setState({value: nextProps.value});
        }
      }
      render() {
        return <div>The value is: {this.state.value}</div>
      }
    }

    出处:https://segmentfault.com/a/1190000015606509

  • 相关阅读:
    求某个数的位数公式
    ArrayList和lInkedList比较
    队列
    抽象数据结构-栈
    LinkedList的实现
    ArrayList的实现
    Iterator和List的一些问题
    SCHEMA约束
    DTD约束
    XML解析
  • 原文地址:https://www.cnblogs.com/mengff/p/9611838.html
Copyright © 2011-2022 走看看