第三方子组件不变,ReactJS中的父项的道具更改

时间:2018-11-02 08:16:46

标签: reactjs

Am使用第三方组件来呈现树表及其正常流程,父级通过传递所需的Props来调用Child组件。

道具: 1.树(包含要渲染为树的实际数据) 2. sortOrder

import React, { Component } from 'react';
import TreeDataTable from 'cp-react-tree-table';

    class TreeView extends Component {
        static propTypes = {
          tree: PropTypes.array,
          sortOrd:PropTypes.any
        };

        static defaultProps = {
            tree: [],
            height: 0
        };

        constructor(props) {
          super(props);
          this.table = React.createRef();
          this.state = {
            sortOrder: ''
          };
        }

        componentDidMount() {
            this.props.tableRef(this.table);
        }
        componentWillReceiveProps({sortOrd}){
            this.setState({sortOrder:sortOrd});
        }

        render() {
          const { tree } = this.props;
          return (
            <div className="treeview">
            // data attribute passes the data to form tree
              <TreeDataTable ref={this.table} data={tree} className="treeview-body">
                <TreeDataTable.Column basis="80%" renderCell={this.renderIndexColumn} />
              </TreeDataTable>
            </div>
          );
        }

我试图根据父组件中的按钮单击(状态更改)对树表重新排序。

有效的方法: 1.父组件中的状态更改 2.父组件重新渲染 3.使用更新的道具(data,sortOrder)调用子组件

  1. 子组件被调用
  2. 子组件状态根据更新的道具而改变
  3. 子组件重新呈现

问题: 子组件会用旧的道具(数据)重新渲染

预期结果: 用更新的道具(数据)重新渲染的子组件

作为常规的Child组件,应该可以使用,但是由于使用的是第三方组件,因此我怀疑缺少一些东西来使其使用更新的数据重新呈现。

有没有办法,我可以使用更新的props(data)重新渲染此子组件,并显示更新的Tree。

2 个答案:

答案 0 :(得分:0)

componentWillReceiveProps为您提供nextProps,但您将其作为对象获得

更改

     componentWillReceiveProps({sortOrd}){
           this.setState({sortOrder:sortOrd});
     }

收件人

     componentWillReceiveProps(nextProps){
           if(nextProps.sortOrd != this.props.sortOrd){          
                  this.setState({sortOrder:sortOrd});

            }
       }

但是请记住,不赞成使用componentWillReceiveProps生命周期方法,因此建议使用替代生命周期方法

     static getDerivedStateFromProps(nextProps, prevState) {
          if(nextProps.sortOrd != this.props.sortOrd){
                 return {
                      sortOrder : nextProps.sortOrd //this is equivalent to setState
                 };
            }else{
                 return null;
            }
        }

答案 1 :(得分:0)

问题出在componentWillReceiveProps中,componentWillReceiveProps中的setState将导致状态更新,但不会调用render。也许您可以像下面那样设置sortOrder,并首先传递null。

constructor(props) {
      ...
      this.state = {
        sortOrder: props.sortOrd
      };
    }

然后,在父组件中更改道具后,树表将重新呈现。

相关问题