子组件的 props 不与父组件的状态耦合

Props of a child component are not coupled with state of parent

我有一个包含 state 的父组件 (App)。在这个组件中,我有一些代码通过事件处理程序来操纵状态。到目前为止一切顺利。

但是,我需要在子组件(ChildComponent)中显示当前state。我试图通过将状态作为 属性 传递给 ChildComponent 来实现这一点,但是我失去了与状态的动态耦合。对状态的任何更改都不会反映在子组件中。

class ChildComponent extends React.Component {
    constructor(props) {
        super(props);
    }

    render () {
        // This should get dynamically updated
        return <div>{this.props.value.toString()}</div>
    }
}


class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: 1};
    }

    // Do stuff here that changes state

    render() {
         return <ChildComponent value={this.state.value} />
    }
}

works now: Updated correct example on codepen

此示例是我的问题的基本表示。我想我遵循了官方文档的示例,特别是 lifting state up。但不知何故它不起作用。可能是我误解了文档(那些也恰好不太好)。

编辑:可能与子组件是 class 而不是函数有关?

您不应直接改变组件的状态 (this.state.x = this.state.x + 1),而应使用 setState.

请参阅 了解更多信息,以及 React 文档 使用 就该主题发表的内容。

你应该使用 setStatesetState 总是触发重新渲染:

https://codepen.io/anon/pen/gmOzXg

这如您所愿:

class ChildComponent extends React.Component {
    constructor(props) {
        super(props);
    }

    render () {
        // This should get dynamically updated
        return <div>{this.props.value.toString()}</div>
    }
}


class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {value: 1};
        this.addOne = this.addOne.bind(this);
    }

    addOne(event){
      this.setState({value: this.state.value+1})
      console.log(this.state.value)
    }

    // Do stuff here that changes state

    render() {
         return (
             <div>
                 <button onClick={this.addOne}>add 1</button>
                 <ChildComponent value={this.state.value} />
             </div>
         )
    }
}

ReactDOM.render(
    <App />,
    document.getElementById('root')
);

你可以测试一下here