【问题标题】:When I press the back button, the page does not change though url is coming correct当我按下后退按钮时,尽管 url 正确,但页面并没有改变
【发布时间】:2020-02-04 20:37:53
【问题描述】:

我尝试为 react 中的数据实现分页。如果我单击任何页面,将打开所需的页面并显示数据。例如,如果我按 page 3 ,则会加载第 3 页上的数据。之后,当我按 5 时,将加载第 5 页上的数据。现在,如果我按下后退按钮,URL 会显示 page 3 ,但安装的组件是 page 5。有人可以帮我吗?

这是我安装的组件:

componentDidMount = async () => {

const { state } = this.props.location;
if (state && state.mesg) {
  this.setState({
    mesg: this.props.location.state.mesg,
    mesgType: this.props.location.state.mesgType
  });
  const stateCopy = { ...state };
  delete stateCopy.mesg;
  this.props.history.replace({ state: stateCopy });
}
this.closeMesg(10000);
let pageNo = this.props.location.search.split("=");
await this.fetchCompaniesAPI(pageNo[1] || 1);
this.setState({ isLoading: false });


};

这里我从 url 中提取页码并调用该页面的 API。

谁能帮帮我。

如果您需要更多详细信息,请告知。

我尝试了 window.onpopstate 然后刷新,但没有帮助

我用 componentDidUpdate 试过了,但还是不行

componentDidUpdate= async (prevProps, prevState)=> {
    await this.setState({ isLoading: true });
    let pageNo = this.props.location.search.split("=");
    if (prevState.pageNo !== pageNo[1]) {
    await this.fetchCompaniesAPI(pageNo[1] || 1);
    this.setState({ isLoading: false });
    }
  }

【问题讨论】:

  • 你从后端获取数据了吗?

标签: reactjs pagination


【解决方案1】:

如果您在同一条路线上,则 url 会更改,但不会重新安装组件,因此您的 componentDidMount 代码不会执行。

您必须为此使用 componentDidUpdate。

检查您的页码是否已更改并再次获取。

componentDidUpdate = async(prevProps: Props, prevState: State) => {
    if (prevProps.location !== this.props.location) {
      const pageNo = this.props.location.search.split("=");
      await this.fetchCompaniesAPI(pageNo[1] || 1);
    }
  }

因为当你按下返回时你的道具会改变,而不是你的状态。

【讨论】:

  • 如何获取prevProps??
  • prevProps 由生命周期方法本身传递,每当组件发生变化时,都会以 prevProps 和 prevState 作为参数调用 componentDidUpdate。
  • this.props.match.params.page 给出未定义
  • 这个参数是空的,我想我没有传递参数来反应路由器。你能帮我传递参数吗?
【解决方案2】:

您需要在组件更新中复制相同的逻辑,并且您只需要在更改为pageNo时执行该逻辑。

例如:

componentDidUpdate(prevProps, prevState) {
  if (prevState.pageNo !== this.state.pageNo) {
    console.log('page number has changed, do logic here...')
  }
}

【讨论】:

  • componentDidUpdate= async (prevProps, prevState)=> { if (prevState.pageNo !== this.state.pageNo) { let pageNo = this.props.location.search.split("=" );等待 this.fetchCompaniesAPI(pageNo[1] || 1); this.setState({ isLoading: false }); } }
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多