javascript - 带条件位置的导航上的 SetState

标签 javascript reactjs gatsby

为什么 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 });
  }
};

最佳答案

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

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

关于javascript - 带条件位置的导航上的 SetState,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54784995/

相关文章:

javascript - 超出最大调用堆栈大小 - reactjs

javascript - 过期时禁用按钮

javascript - React Native 性能缓慢

reactjs - React 组件意外共享状态

javascript - Gatsby 3.X + Netlify

javascript - 简单地从数组中删除空值 - javascript

css - 在Reactjs中使用CSS className设置react-select组件的样式

javascript - 获取动态填充的输入值 React.js

gatsby - 如何在 Gatsby.JS 项目中从索引页重定向到以编程方式生成的路由

Gatsby 插件站点地图不会为我的网站生成站点地图