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

标签 javascript reactjs

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

相关文章:

javascript - 嘿谁能告诉我为什么我不从 api 渲染数据

javascript - react .js : reusable components vs mixin's utility functions

javascript - 使用状态响应所需的验证

javascript - 从一种 PHP 表单涉及的多个选择框中获取至少一个值

javascript - 使用 phantom js 获取 css 值

javascript - JQuery 动画与 slidedown

reactjs - Redux 使用 jest、nock、axios 和 jsdom 测试 multipart/form-data

javascript - 递归 require 找不到 Browserify 模块(Babel 后转译)

javascript - 使用 javascript 切换主 div 内其他 div 的显示

javascript - 从 onclick 事件中选择 select 语句中的选项