【发布时间】:2018-11-08 19:56:42
【问题描述】:
我将 props 从 Parent 组件传递到 Child 的状态,但它们不同步。
我尝试了什么:
- State Updates May Be Asynchronous,我已经使用回调而不是返回对象来解决这个问题。
- Objects are passed by reference,但是我使用的道具是一个字符串。
我正在使用 React 16 和 es6 语法
class Parent extends React.Component {
state = {
isHidden: false
}
render() {
console.log('PROPS from PARENT', this.state.isHidden)
return <div>
<Child isOpen={this.state.isHidden} />
<button onClick={this.toggleModal}>Toggle Modal</button>
</div>
}
toggleModal = () => this.setState(state => ({isHidden: !state.isHidden}))
}
class Child extends React.Component {
state = {
isHidden: this.props.isOpen
}
render() {
console.log('STATE of CHILD:',this.state.isHidden)
return <p hidden={this.state.isHidden}>Hidden:{this.state.isHidden}</p>
}
}
ReactDOM.render(<Parent/>, document.getElementById('app'));
这里是一个代码笔PEN - 注意重新渲染的元素应该根据状态隐藏(状态取决于父级的道具)
【问题讨论】:
-
请注意,设置直接从 props 派生的状态通常不是正确的方法,因为您始终可以直接从 props 使用值,只有在 props 需要更改的情况下才应该这样做仅在特定动作后从道具中获得
-
这正是我的代码所做的,将状态设置为道具,然后根据特定操作设置状态@ShubhamKhatri 谢谢。
-
通过一个特定的动作,我的意思是触发从子级到父级的更新而不是相反的动作。例如,您可能希望根据 props 预填充表单数据,然后编辑这些数据并在提交操作上将数据发送回父级。
-
我没有触发孩子的动作吗?我不明白
标签: reactjs ecmascript-6 react-props react-state-management