React router + redux 向后导航不调用 componentWillMount

React router + redux navigating back doesn't call componentWillMount

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

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

当用户导航到路线 /:dept/:course 时调用它,并且它工作正常,直到您从假设导航:/mif/31/mif/33 然后按后退按钮。该组件实际上并没有重新初始化,因此没有调用生命周期方法,也没有重新加载数据。

在这种情况下是否有某种方法可以重新加载数据?我是否应该使用另一种预加载数据的方法?我看到反应路由器在任何位置更改时发出 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);
  };
}

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

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

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

免责声明:我对 redux 的了解可能比你少。

您需要使用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))
  }
}