React router + redux导航回来不会调用componentWillMount [英] React router + redux navigating back doesn't call componentWillMount
问题描述
目前我在容器组件的生命周期方法componentWillMount中从api预加载数据:
Currently I pre-load data from api in container component's lifecycle method componentWillMount:
componentWillMount() {
const { dept, course } = this.props.routeParams;
this.props.fetchTimetable(dept, course);
}
用户导航到路由 /时调用: dept /:course
,它工作正常,直到你从let说: / mif / 31
导航到 / mif / 33
然后按返回按钮。该组件实际上并未重新初始化,因此不会调用生命周期方法,并且不会重新加载数据。
It is called when user navigates to route /:dept/:course
, and it works fine, until you navigate from let's say: /mif/31
to /mif/33
and then press back button. The component is not actually reinitialized, so the lifecycle method is not called, and the data isn't reloaded.
在这种情况下是否有某种重新加载数据的方法?我可以使用另一种预加载数据的方法吗?我看到react路由器在任何位置更改时发出 LOCATION_CHANGE
事件,包括导航回来,所以也许我可以以某种方式使用它?
Is there some sort of way to reload data in this case? Should I maybe use another method of preloading data? I see react router emits LOCATION_CHANGE
event on any location change, including navigating back, so maybe I can somehow use that?
如果重要,这就是我如何实现数据加载:
If it matters, here's is how I implement data loading:
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
You need to use componentWillReceiveProps
to check if new props (nextProps
) are same as existing props (this.props
). Here's relevant code in Redux example: 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))
}
}
这篇关于React router + redux导航回来不会调用componentWillMount的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!