使用 React 子组件上的道具更新状态 [英] Updating state with props on React child component
问题描述
我有一个 React 应用程序,其中来自父组件的 props 传递给子组件,然后 props 设置子组件的状态.
在我向父组件发送更新的值后,子组件不会使用更新的 props 更新状态.
如何让它更新子组件的状态?
我的精简代码:
class Parent extends React.Component {构造函数(道具){超级(道具);this.state = {名称:''}}组件DidMount(){this.setState({name: this.props.data.name});}句柄更新(更新名称){this.setState({name: updatedName});}使成为 () {return <Child name={this.state.name} onUpdate={this.handleUpdate.bind(this)}/>}}class Child 扩展 React.Component {构造函数(道具){超级(道具);this.state = {名称:''}}组件DidMount(){this.setState({name: this.props.name});}句柄变化(e){this.setState({[e.target.name]: e.target.value});}句柄更新(){//ajax 调用使用更新的名称更新数据库,然后成功调用 onUpdate(updatedName)}使成为 () {console.log(this.props.name);//更新后,这会记录更新后的名称控制台日志(this.state.name);//更新后,这会记录初始名称,直到我刷新浏览器返回 {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)}/>}}
你需要实现 componentWillReceiveProps
在您的孩子中:
componentWillReceiveProps(newProps) {this.setState({name: newProps.name});}
componentWillReceiveProps
现在已弃用并将被删除,但上面的文档链接中有其他建议.
I have a React app, where props from a parent component are passed to a child component and the props then set the state on the child.
After I send an updated value to the parent component, the child component isn't updating the state with the updated props.
How do I get it to update the state on the child component?
My pared-down code:
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>
}
}
You need to implement componentWillReceiveProps
in your child:
componentWillReceiveProps(newProps) {
this.setState({name: newProps.name});
}
Edit: componentWillReceiveProps
is now deprecated and will be removed, but there are alternative suggestions in the docs link above.
这篇关于使用 React 子组件上的道具更新状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!