目前,我在容器组件的生命周期方法 componentWillMount 中预加载来自 api 的数据:
componentWillMount() {
const { dept, course } = this.props.routeParams;
this.props.fetchTimetable(dept, course);
}
当用户导航到路线时调用它/:dept/:course
,并且它工作正常,直到您从以下位置导航:/mif/31
to /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);
};
}
你需要使用componentWillReceiveProps
检查是否有新的道具(nextProps
) 与现有的 props 相同 (this.props
)。 Redux 示例中的相关代码如下:https://github.com/reactjs/redux/blob/e5e608eb87f84d4c6ec22b3b4e59338d234904d5/examples/async/src/containers/App.js#L13-L18 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))
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)