Javascript 设置带条件位置的导航状态
为什么Gatsby上的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
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!==位置
。