小编典典

在React子组件上使用props更新状态

reactjs

我有一个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>
    }
}

阅读 732

收藏
2020-07-22

共1个答案

小编典典

您需要componentWillReceiveProps在孩子中实施:

componentWillReceiveProps(newProps) {
    this.setState({name: newProps.name});
}

编辑: componentWillReceiveProps现在已弃用,将被删除,但是上面的docs链接中有替代建议。

2020-07-22