首页 文章

JavaScript | ReactJS:父状态 - 更改不触发子道具更新

提问于
浏览
0

Parent setState触发render(),但Child Component的Props是静态的

这非常简单 . 我有 <Parent /> 有一个state-property和一个处理程序 . 父对象将属性和处理程序传递给子进程 .

孩子有一个按钮并调用自己的处理程序,它包装了Parent的处理程序 . 布尔值 isNew 传递给Parent - Parent调用 this.setState({ isNew: isNew }) .

父总是调用 render 并在Parent的HTML中输出 isNew 显示一切正确 . 但是, <Child isNew={this.state.isNew} /> 永远不会从 this.props.isNew 输出正确的值 - 它总是在Parent的 getInitialProps 方法内的Parent中初始化的值 .

我刚刚进入这个项目,但我没有在内部实施Flux或Redux . 我的假设是React,开箱即用, should rerender all children whose props are set to the parent's state .

换句话说,如果我有以下内容:

React.createClass({
    render: function () {
        return (<Child isNew={this.state.isNew} handler={this.handler} />);
    }
});

当父母重新呈现[来自状态变化]时,所有依赖父母状态的孩子也应该重新渲染,同时将父母的新状态封装在其道具中;假设 <Child property={this.state.property} /> 的儿童道具

我完全错过了一些基本的东西吗?

请直截了当:)

谢谢

1 回答

  • 0

    我想你在子构造函数中设置this.props.isNew并尝试打印它..

    大孩子:

    import React, { Component } from 'react';
    
    class GrandChild extends Component {
      constructor(props) {
        super(props);
        this.toogle = this.toogle.bind(this);
      }
    
      toogle(e) {
        if (e) {
          e.preventDefault();
        }
        this.props.toogleParent(!this.props.isNew);
      }
    
      render() {
        console.log('in grand child', this.props.isNew);
        return (
          <div>
            <a onClick={this.toogle} href="">click</a>
          </div>
        );
      }
    }
    
    export default GrandChild;
    

    子组件:

    import React, { Component } from 'react';
    import GrandChild from './grand';
    
    
    class Child extends Component {
      render() {
        console.log('in child', this.props.isNew);
        return (
          <div>
            <GrandChild {...this.props} />
          </div>
        );
      }
    }
    
    export default Child;
    

    父组件:

    import React, { Component } from 'react';
    import Child from './child';
    
    class MainPage extends Component {
      constructor(props) {
        super(props);
        this.state = {
          isNew: false
        };
        this.toogleParent = this.toogleParent.bind(this);
      }
    
      toogleParent(isNew) {
        this.setState({ isNew });
      }
    
      render() {
        console.log('in parent', this.state.isNew);
        return (
          <div>
            <h3>Main page</h3>
            <Child isNew={this.state.isNew} toogleParent={this.toogleParent} />
          </div>
        );
      }
    }
    
    export default MainPage;
    

    输出:

    在父母的真实在孩子真实在大孩子真实在父母虚假在孩子虚假在盛大孩子虚假等 .

相关问题