React只渲染一个子组件一次

问题描述 投票:0回答:2

我正在尝试按需填充TreeView组件。我在componentDidMount函数中获取数据,然后将这些数据插入主组件状态的数组中。 componentDidUpdate用于将数据数组设置为treeview根节点。事实是,树视图不会呈现数据,除非它以静态方式呈现,根据需要它不会显示任何内容。这是代码:

constructor (props) {
    super(props);
    this.state = {
      data: []
    };
    this.tree = {
      idx: 0,
      descript: 'Root',
      collapsible: true,
      collapsed: false
    };
  }

  receivingData = (data = []) => {
    this.setState({data: data});
  }

  componentDidMount () {
    fetchData(this.receivingData);
  }

componentDidUpdate (prevProps, prevState) {
    if (prevState.data.length !== this.state.data.length) {
      this.tree.children = [];
      for (let x of this.state.data) {
        this.tree.children.push({
          idx: x.idx,
          descript: x.name,
          collapsible: true,
          collapsed: false
        });
      }
    }
  }

这是渲染方法:

render () {
   console.log('getting here', this.tree);
    return (
      <div>
            <TreeView
              onNodeSelectionChange={this.onTreeNodeSelection} ref={this.treeViewContainerRefBuilder}
              data={this.tree} selectLeavesOnly={false} singleSelect/>
        </div>
      </div>
    );
  }

控制台日志显示树的更改,但TreeView只呈现一次。我究竟做错了什么?

reactjs components render
2个回答
0
投票

我相信你在这里遇到的问题是,当receivingData将导致重新渲染时,你正在this.tree方法中编辑componentDidUpdate,该方法在重新渲染已经发生之后发生,因此你的TreeView组件不会重新渲染更新的数据。

尝试使用componentWillUpdate而不是componentDidUpdate,以便在重新渲染之前修改this.tree


0
投票

这应该可以解决您的问题:

constructor (props) {
super(props);
this.state = {
  data: []
};
this.tree = {
  idx: 0,
  descript: 'Root',
  collapsible: true,
  collapsed: false
};
}

receivingData = (data = []) => {
if (prevState.data.length !== data.length) {
    this.tree.children = [];
    for (let x of this.state.data) {
      this.tree.children.push({
        idx: x.idx,
        descript: x.name,
        collapsible: true,
        collapsed: false
      });
    }
  }
this.setState({data: data});
}

componentDidMount () {
 fetchData(this.receivingData);
}

componentDidUpdate (prevProps, prevState) {

}

注意:不要使用componentWillUpdate,因为这些方法被认为是遗留的,您应该在新代码中避免使用它们。请参阅https://reactjs.org/docs/react-component.html

希望这可以帮助 :)

© www.soinside.com 2019 - 2024. All rights reserved.