Javascript 设置带条件位置的导航状态

Javascript 设置带条件位置的导航状态,javascript,reactjs,gatsby,Javascript,Reactjs,Gatsby,为什么Gatsby上的state={pageIndex:0}不按照this.handlePageIndex()进行更新,而在安装到浏览器刷新时,它将进行导航 state = { pageIndex: 0 }; componentDidMount() { this.handlePageIndex(); } // Have tried but doesn't seem necessary. // componentDidUpdate(prevProps) { // const { loc

为什么Gatsby上的
state={pageIndex:0}
不按照
this.handlePageIndex()
进行更新,而在安装到浏览器刷新时,它将进行导航

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 });
  }
};

您可能需要添加
componentdiddupdate
static getDerivedStateFromProps
来处理位置更改


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

谢谢,正如您所提到的
,这是一个简单的错误!prevLocation&&location
应该是
prevLocation!==位置