首页 > 解决方案 > 反应子状态不会使用父亲的道具更新(并且在分支中更深)

问题描述

问题如下:我有组件:祖父,父亲和孩子(字面意思是:D)。祖父通过道具将他的状态传递给父亲(父亲用它设置他的状态)。然后父亲将道具传递给孩子,孩子也用它设置状态。当我显示 this.props 时,一切都很好,但是当我显示状态时,我看到父亲和孩子没有任何变化。我听说有类似 componentWillReceiveProps() 的东西,但它已经被弃用了。

工作示例:https ://codesandbox.io/s/doesitworkornot-rrcgt?fontsize=14&hidenavigation=1&theme=dark

和代码:

祖父.js

import React from "react";
import Father from "./Father";

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

  onClick = e => {
    this.setState(prevState => ({
      clickedCounter: prevState.clickedCounter + 1
    }));
  };

  render() {
    return (
      <div>
        <button onClick={this.onClick}>Press me</button> <br />
        Here is Grandfather -> state value={this.state.clickedCounter}
        <Father clickedCounter={this.state.clickedCounter} />
      </div>
    );
  }
}
export default GrandFather;

父亲.js

import React from "react";
import Child from "./Child";

class Father extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clickedCounter: this.props.clickedCounter
    };
  }
  render() {
    return (
      <div>
        Here is Father -> props value={this.props.clickedCounter} <br />
        Here is Father -> state value={this.state.clickedCounter}
        <Child clickedCounter={this.props.clickedCounter} />
      </div>
    );
  }
}
export default Father;

Child.js

import React from "react";

class Child extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      clickedCounter: this.props.clickedCounter
    };
  }
  render() {
    return (
      <div>
        Here is Child -> props value={this.props.clickedCounter} <br />
        Here is Child -> state value={this.state.clickedCounter}
      </div>
    );
  }
}

export default Child;

我还听说有类似克隆孩子的事情......如果可能的话,我想避免它。

标签: javascriptreactjsreact-native

解决方案


当你从 props 初始化 state 时,react 不会刷新 state,但它会刷新 props。您可以使用以下代码代替 componentWillReceiveProps 使其工作。

static getDerivedStateFromProps(nextProps) {    
    return {
      clickedCounter: nextProps.clickedCounter,
    }
}

推荐阅读