简体   繁体   English

父状态更改不更新子道具

[英]Parent state change not updating child props

I'm trying to update a child based on the props provided by it's parent.我正在尝试根据其父母提供的道具更新孩子。 The way it works right now is that the parent's state contains a variable called 'paused' which is provided to the child like this:它现在的工作方式是父级的状态包含一个名为“暂停”的变量,它像这样提供给子级:

class Parent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      history: this.props.history,
      paused: false,
    }
  }
    render() {
        let paused = this.state.paused
        return (
          <ChildContainer
            graph={
              <Child
                paused={paused}
              />
            }
          />
        )
      }

Child then uses it like this: Child 然后像这样使用它:

render() {
    return (
          <div>
            {'paused:' + this.props.paused}
          </div>
    )
  }

Paused is a boolean, the usage above is just for testing, since I couldn't get it to update where I want, the behaviour is the same like this. Paused 是一个布尔值,上面的用法只是为了测试,因为我无法让它更新到我想要的地方,行为是这样的。

Paused is being updated in the parent, but not the child. Paused 正在父级中更新,但不是在子级中更新。 I've read a lot of questions like this, but I'm at a loss.我已经阅读了很多这样的问题,但我不知所措。

Any help would be greatly appreciated.任何帮助将不胜感激。

I can't seem to find a problem with this based on the code you've provided.根据您提供的代码,我似乎无法找到此问题。 Here is working proof.这是工作证明。

If ChildContainer has any logic that could interfere then I could be wrong, but as is, this works:如果ChildContainer有任何可能干扰的逻辑,那么我可能是错的,但按原样,这是有效的:

 class Parent extends React.Component { constructor(props) { super(props) this.state = { history: this.props.history, paused: false, } } render() { let paused = this.state.paused // I agree with @Kuo-hsuan Hsu this is unnecessary return ( <ChildContainer toggle={() => this.setState({ paused: !this.state.paused })} graph={<Child paused={paused}/>} /> ) } } class ChildContainer extends React.Component { render() { return ( <div> {this.props.graph} <button onClick={this.props.toggle}>Toggle</button> </div> ); } } class Child extends React.Component { render() { return ( <div>{'paused:' + this.props.paused}</div> ) } } ReactDOM.render(<Parent />, document.getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="root" />

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM