React router + redux导航返回不会调用componentWillMount

React router + redux navigating back doesn't call componentWillMount

本文关键字:调用 componentWillMount 返回 导航 router redux React      更新时间:2023-09-26

目前我在容器组件的生命周期方法componentWillMount:

中预加载来自api的数据
componentWillMount() {
  const { dept, course } = this.props.routeParams;
  this.props.fetchTimetable(dept, course);
}

当用户导航到路由/:dept/:course时调用,它工作正常,直到您从例如:/mif/31导航到/mif/33,然后按回键。组件实际上没有被重新初始化,因此不会调用生命周期方法,也不会重新加载数据。

在这种情况下是否有某种方法可以重新加载数据?我是否应该使用另一种预加载数据的方法?我看到react路由器在任何位置更改上发出LOCATION_CHANGE事件,包括导航返回,所以也许我可以使用它?

如果重要的话,下面是我实现数据加载的方法:

import { getTimetable } from '../api/timetable';
export const REQUEST_TIMETABLE = 'REQUEST_TIMETABLE';
export const RECEIVE_TIMETABLE = 'RECEIVE_TIMETABLE';
const requestTimetable = () => ({ type: REQUEST_TIMETABLE, loading: true });
const receiveTimetable = (timetable) => ({ type: RECEIVE_TIMETABLE, loading: false, timetable });
export function fetchTimetable(departmentId, courseId) {
  return dispatch => {
    dispatch(requestTimetable());
    getTimetable(departmentId, courseId)
      .then(timetable => dispatch(receiveTimetable(timetable)))
      .catch(console.log);
  };
}

您需要使用componentWillReceiveProps来检查新道具(nextProps)是否与现有道具(this.props)相同。以下是Redux示例中的相关代码:https://github.com/reactjs/redux/blob/e5e608eb87f84d4c6ec22b3b4e59338d234904d5/examples/async/src/containers/App.js#L13-L18

componentWillReceiveProps(nextProps) {
  if (nextProps.dept !== this.props.dept || nextProps.course !== this.props.course) {
    dispatch(fetchTimetable(nextProps.dept, nextProps.course))
  }
}

我可能在这里错了,但我相信你正在寻找的功能不是componentWillMount而是componentWillReceiveProps,

假设你正在传递变量(如:courseId)从redux路由器到你的组件,使用setState在componentWillReceiveProps应该重新绘制你的组件。

否则,您可以订阅您的商店中的更改:http://redux.js.org/docs/api/Store.html

免责声明:我可能比你更了解redux。