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

  • 相关阅读:
    MongoDB
    Mac下将Python2.7改为Python3
    Kafka
    Server 基础概念 备忘
    应用内支付
    Sign in with apple
    Linux三剑客grep/sed/awk
    React-Native中使用到的一些JS特性
    Date Picker控件:
    Picker View控件:
  • 原文地址:https://www.cnblogs.com/mengff/p/9611838.html
Copyright © 2011-2022 走看看