我有一个React应用程序,其中来自父组件的道具被传递给子组件,然后道具设置子组件的状态。使用React子组件上的道具更新状态
将更新后的值发送给父组件后,子组件未更新具有更新的道具的状态。
如何获取它来更新子组件上的状态?
我的削减的代码:
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>
}
}
你知道那些你只想说“我爱你”的随机SO海报,这是其中的一次。谢谢你仁慈的人。 – markau
整天都在找这个!试图将状态更新为孩子,并且这样做了 – William