Ada*_*ite 41 javascript reactjs
我有一个React应用程序,其中父组件的道具传递给子组件,然后道具设置子项的状态.
将更新后的值发送到父组件后,子组件不会使用更新的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>
}
}
Run Code Online (Sandbox Code Playgroud)
Blo*_*ard 63
你需要componentWillReceiveProps在孩子身上实施:
componentWillReceiveProps(newProps) {
this.setState({name: newProps.name});
}
Run Code Online (Sandbox Code Playgroud)
修改: componentWillReceiveProps现已弃用,将被删除,但上面的文档链接中还有其他建议.
小智 7
调用setState()在componentWillReceiveProps不会造成额外的重新渲染.接收道具是一个渲染,如果在componentDidUpdate之类的方法中执行,则this.setState将是另一个渲染.我建议this.state.name !== nextProps.name在shouldComponentUpdate中进行操作,以便始终检查是否有任何更新.
componentWillReceiveProps(nextProps) {
this.setState({name: nextProps.name});
}
shouldComponentUpdate(nextProps) {
return this.state.name !== nextProps.name;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
32308 次 |
| 最近记录: |