为什么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 });
}
};
答案 0 :(得分:2)
您可能需要添加componentDidUpdate
或static getDerivedStateFromProps
来处理位置更改。
请注意,componentDidUpdate
也会在状态更改时触发,因此您应在此处设置状态之前检查prevLocation !== location
是否存在,否则将导致无限循环。