标签:nbsp 完美解决 style 赋值 变化 stat receive 创建 val
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
标签:nbsp 完美解决 style 赋值 变化 stat receive 创建 val
原文地址:https://www.cnblogs.com/mengff/p/9611838.html