如何在componentDidMount中访问道具

时间:2020-08-03 07:31:51

标签: reactjs

我是新来的反应者,在将道具传递给子组件时遇到问题

我有2个组成部分:PhotoListPagination。在PhotoList组件中,我传递的2个道具是currentPagetotalPage对于Pagination组件。

<Pagination 
  totalPage={Math.floor(this.state.totalImages/30)+1}
  currentPage={this.state.currentPage}
  clicked={this.pageChanged}
/>

内部Pagination组件。我有一个州,我想根据range的值计算currentPage属性

state = {
    range: [],
    startPage: 1,
    maxVisibleButtons: 5
  }

问题是当我在componentDidMount中访问道具时。我收到totalPage为1而不是正确值(在我的情况下为37),并且状态中的range属性值错误

还有另一件事是什么想法,只要range的值更改,就重新计算currentPage的值?

1 个答案:

答案 0 :(得分:0)

可能 this.state.totalImages 的值在初始渲染时不可用,因此您需要在相关 range 发生变化时重新计算 props

class Pagination extends React.Component {
  state = {
    range: [],
    startPage: 1,
    maxVisibleButtons: 5
  }

  // Compute range and save into state
  computeRange() {
    const {totalPage} = this.props;
    const newRange = [/* Some range computation based on props*/];
    this.setState({ range: newRange });
  }

  // Initially compute range
  componentDidMount() {
    computeRange();
  }

  // Recompute range if total changed
  componentDidUpdate(prevProps, prevState) {
    if(this.props.totalPage !== prevProps.totalPage) {
      computeRange();
    }
  }
}

或者使用功能组件和React.useMemo

const Pagination = ({totalPage, currentPage, clicked}) => {
  const [startPage, setStartPage] = React.useState(1);
  const [maxVisibleButtons, setMaxVisibleButtons] = React.useState(5);
  const range = React.useMemo(() =>
    // Or whatever you do to compute the range
    new Array(totalPage)
      .fill(0)
      .map((el, index) => index+1
  ), [totalPage]);

  return (
    /* The render return */
  );
}