React父组件state变更后,传入子组件的props更新但子组件未重渲染是什么原因?
问题根因
你在Child组件中将父组件传入的props.value复制到了组件自身的state中,但类组件的constructor仅会在组件首次挂载时执行1次,后续父组件更新myState并传递新的props.value到子组件时,子组件不会重新执行constructor同步更新自身state,因此会出现props变更但子组件展示内容没有变化的问题。
解决方案
根据你的业务场景可以选择两种实现方案:
方案1:子组件直接使用props(推荐,符合React单向数据流原则)
如果子组件的value最终值需要和父组件状态保持同步,优先选择受控组件写法,子组件不单独维护自身state,直接渲染props传入的值即可。如果子组件需要修改值,通过父组件传入的回调方法更新父组件状态后自然会同步到子组件:
class Child extends React.Component { constructor(props) { super(props) this.randomize = this.randomize.bind(this) } randomize() { // 如需修改值,调用父组件传入的更新回调即可,示例: // this.props.updateValue(Math.random() * 100) } render() { return( <div> <h1>My value is {this.props.value}</h1> <button onClick={this.randomize}>This changes the state of Child</button> </div> ) } }
父组件对应修改传参即可:
// App组件render方法内 <Child value={this.state.myState} updateValue={(newVal) => this.setState({myState: newVal})}/>
方案2:子组件维护独立状态,监听props变化同步
如果你的业务场景需要子组件可以独立修改状态,同时也要响应父组件的props更新,可以通过componentDidUpdate生命周期监听props变化,同步更新子组件自身state:
class Child extends React.Component { constructor(props) { super(props) this.state = { value: this.props.value } this.randomize = this.randomize.bind(this) } // 新增生命周期监听props变化 componentDidUpdate(prevProps) { // 仅当props的value发生变化时才同步更新子组件state,避免无限循环 if (prevProps.value !== this.props.value) { this.setState({value: this.props.value}) } } randomize() { this.setState({value: Math.random() * 100}) } render() { return( <div> <h1>My value is {this.state.value}</h1> <button onClick={this.randomize}>This changes the state of Child</button> </div> ) } }
内容的提问来源于stack exchange,提问作者gnot
相关产品推荐
相关产品推荐

