【问题标题】:React renders a child component only one timeReact 只渲染一个子组件一次
【发布时间】:2017-11-03 19:51:57
【问题描述】:

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

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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢 CD-jS 先生,我按照您的建议做了,一切都一样。我把树放在状态中,也没有任何反应。
    【解决方案2】:

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

    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

    希望这会有所帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-04
      • 1970-01-01
      • 2019-04-27
      • 2018-04-04
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多