使用条件位置导航时的SetState

时间:2019-02-20 11:14:12

标签: javascript reactjs gatsby

为什么state = { pageIndex: 0 }不能按照this.handlePageIndex()在盖茨比navigate上进行更新,而在安装浏览器时会刷新?

state = { pageIndex: 0 };

componentDidMount() {
  this.handlePageIndex();
}

// Have tried but doesn't seem necessary.
// componentDidUpdate(prevProps) {
//   const { location: prevLocation } = prevProps;
//   const { location } = this.props;
//   if (!prevLocation && location) {
//     this.handlePageIndex();
//   }
// }

componentWillUnmount() {
  this.handlePageIndex();
}

handlePageIndex = () => {
  const { location } = this.props;
  if (location.pathname === '/') {
    this.setState({ pageIndex: 0 });
  } else if (location.pathname === '/slide-two/') {
    this.setState({ pageIndex: 1 });
  } else if (location.pathname === '/slide-three/') {
    this.setState({ pageIndex: 2 });
  }
};

1 个答案:

答案 0 :(得分:2)

您可能需要添加componentDidUpdatestatic getDerivedStateFromProps来处理位置更改。

请注意,componentDidUpdate也会在状态更改时触发,因此您应在此处设置状态之前检查prevLocation !== location是否存在,否则将导致无限循环。