ReactJS-将更新的值传递给子组件方法

时间:2019-05-14 00:21:12

标签: reactjs

我正在一个基本上由以下主要组件设置的环境中工作:

class MainComponent extends Component {
  constructor(props) {
    super(props);

    this.state = {
      selectedValues: []
    };
  }

  render() {
    const { selectedValues } = this.state;
    return (
      // Other components
      <SubComponent selectedValues = {selectedValues} />
      // Other components
    );
  }
}

export default MainComponent;

还有这样的子组件:

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

    this.state = {
      isExporting: false,
      selectedValues: props.selectedValues
    };
  }

  performTask = () => {
    this.setState({ isWorking: true });
    const { selectedValues } = this.state;
    console.log(`Selected Values: ${selectedValues}`);
    fetch('/api/work', {
      method: 'GET'
    })
      .then(res => res.json())
      .then((result) => {
         // Handle the result
         this.setState({ isWorking: false });
      })
      .catch((error) => {
        console.log(error);
        this.setState({ isWorking: false });
      });
  };

  render() {
    const { isWorking } = this.state;
    return (
      <Button
        bsStyle="primary"
        disabled={isWorking}
        onClick={() => this.performTask()}
      >
        {isWorking ? 'Working...' : 'Work'}
      </Button>
    );
  }
}

SubComponent.propTypes = {
  selectedValues: PropTypes.arrayOf(PropTypes.string)
};

SubComponent.defaultProps = {
  selectedValues: []
};

export default SubComponent;

在主组件中,还有其他一些组件可以更改selectedValues。我想看到的功能是,在触发performTask方法时,它具有selectedValues的最新列表。在我当前的设置中,selectedValues始终是一个空列表。无论实际上在主组件中选择了多少个值,列表在子组件中似乎都没有改变。

有一种简单的方法吗?

2 个答案:

答案 0 :(得分:0)

我建议您使用以下两种方法来检查此问题:

  • 也许state.selectedItems根本没有改变。您只在承包商中声明它,但值仍然存在,因为您没有用其他值设置setState。如果您改为引用this.props.selectedItems,则可能会起作用。
  • 尝试将功能组件WillReceiveProps(newProps)添加到子组件并检查其中的值。 如果此方法未调用,则表示selectedItems不变。

如果其中一些有效,请更新。

祝你好运。

答案 1 :(得分:0)

由于已在SubComponent构造函数中设置,因此处于SubComponent状态的

selectedValues 尚未更新。您可能需要在SubComponent的componentWillReceivedProps中再次调用setState