为什么 state = { pageIndex: 0 }
没有根据 this.handlePageIndex()
在 Gatsby 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 });
}
};
最佳答案
您可能需要添加 componentDidUpdate
或 static getDerivedStateFromProps
来处理位置更改。
请注意 componentDidUpdate
也会在状态更改时触发,因此您应该在设置状态之前检查 prevLocation !== location
是否存在,否则您将陷入无限循环.
关于javascript - 带条件位置的导航上的 SetState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54784995/