我有一个 React 应用程序,其中来自父组件的 props 被传递给子组件,然后 props 设置子组件的状态。
在我将更新后的值发送到父组件后,子组件不会使用更新后的属性更新状态。
如何让它更新子组件的状态?
我精简的代码:
class Parent extends React.Component {
constructor (props) {
super(props);
this.state = {name: ''}
}
componentDidMount () {
this.setState({name: this.props.data.name});
}
handleUpdate (updatedName) {
this.setState({name: updatedName});
}
render () {
return <Child name={this.state.name} onUpdate={this.handleUpdate.bind(this)} />
}
}
class Child extends React.Component {
constructor (props) {
super(props);
this.state = {name: ''}
}
componentDidMount () {
this.setState({name: this.props.name});
}
handleChange (e) {
this.setState({[e.target.name]: e.target.value});
}
handleUpdate () {
// ajax call that updates database with updated name and then on success calls onUpdate(updatedName)
}
render () {
console.log(this.props.name); // after update, this logs the updated name
console.log(this.state.name); // after update, this logs the initial name until I refresh the brower
return <div>
{this.state.name}
<input type="text" name="name" value={this.state.name} onChange={this.handleChange} />
<input type="button" value="Update Name" onClick={this.handleUpdate.bind(this)} />
</div>
}
}
最佳答案
您需要实现 componentWillReceiveProps
在您的 child 身上:
componentWillReceiveProps(newProps) {
this.setState({name: newProps.name});
}
编辑:componentWillReceiveProps
现已弃用并将被删除,但上面的文档链接中有替代建议。
关于javascript - 在 React 子组件上使用 props 更新状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39154967/