React - 在更新组件时将props传递给另一个组件

时间:2018-06-15 14:46:43

标签: reactjs redux

我有2个组件,一个是Grid组件,其中显示了一些数据的列表。另一个是"functional"组件,其中包含sorting, paging, etc之类的逻辑,它将位于每个Grid组件中。 Grid组件也可以包含一些自己的特定逻辑。

我的问题是,只要functional组件中的内容发生变化,我就可以将道具传递给Grid组件。现在它只是首次传递道具Grid组件被初始化,之后functional组件与新的道具一起工作。

Grid组件连接到redux商店,但我认为这不重要。

我不确定通过状态初始化类组件是不是很好的方法,还有另外一种方法吗?

代码到网格组件

type ProcessListProps =
  ProcessState.IProcessesStateType
  & typeof ProcessState.actionCreators
  & RouteComponentProps<{}>;

type State = {
    sharedFunctionality: SharedGridFunctions;
}

class ProcessList extends React.Component<ProcessListProps, State> {
  constructor(props) {
  super(props);
      this.state = {
          sharedFunctionality: new SharedGridFunctions(this.props)
      }  
  }

componentDidMount() {
      this.props.requestData(this.props.dataQuery);
  }

componentDidUpdate(oldProps): void {
      if ((oldProps.dataQuery.context !== this.props.dataQuery.context)) {
          this.props.requestData(this.props.dataQuery);
      }

  if (oldProps.sort !== this.props.sort) {
          this.state.sharedFunctionality.buildSortExpression();
      }
  }
..render - removed for brevity
}

功能组件代码

interface ISharedGridFunctions extends IGridBase, IBaseFilterActionCreator, IBaseActionCreator {

}
export default class SharedGridFunctions extends React.PureComponent<ISharedGridFunctions,{}>{
    constructor(props) {
        super(props);
  }

  componentDidUpdate() {
    console.log("shared component updated");
  }

  pageChange = (event) => {
      this.setPaging(event.page.skip, event.page.take);
  };

  setPaging = (skip: number, take: number) => {
      this.props.setPaging(take, skip);
  };

  sortChange = (event) => {
      const dataQuery = this.props.dataQuery;
      this.props.setOrder(dataQuery, event.sort);
  };

  //build sort expression in dataQuery object which is sent to api calls
  buildSortExpression = () => {
        let expression = "";
        this.props.sort.map((sort) =>
            expression += `${sort.field} ${sort.dir}, `
        );
        expression = expression.substring(0, expression.length - 2);
        const dataQuery = this.props.dataQuery;

        if (expression.length > 0) {
            dataQuery.sort.orderBy = expression;
        }
        else {
            dataQuery.sort.orderBy = undefined;
        }
        this.props.setOrder(dataQuery, this.props.sort, true)
    }

    removeByKey = (myObj, deleteKey) => {
        return Object.keys(myObj)
            .filter(key => key !== deleteKey)
            .reduce((result, current) => {
                result[current] = myObj[current];
                return result;
            }, {});
    }

    render() {
        return null;
    }
}

0 个答案:

没有答案