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

时间:2016-09-15 15:10:09

标签: javascript reactjs redux react-router react-router-redux

目前我在容器组件的生命周期方法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);
  };
}

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:0)

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

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

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

免责声明:我可能不太了解redux然后你。