Javascript React路由器&x2B;redux向后导航不';不要调用组件willmount
目前,我从容器组件的生命周期方法componentWillMount中的api预加载数据:Javascript React路由器&x2B;redux向后导航不';不要调用组件willmount,javascript,reactjs,redux,react-router,react-router-redux,Javascript,Reactjs,Redux,React Router,React Router Redux,目前,我从容器组件的生命周期方法componentWillMount中的api预加载数据: componentWillMount() { const { dept, course } = this.props.routeParams; this.props.fetchTimetable(dept, course); } 当用户导航到route/:dept/:course时调用它,它工作正常,直到您从/mif/31导航到/mif/33,然后按后退按钮。组件实际上没有重新初始化,因此不会调
componentWillMount() {
const { dept, course } = this.props.routeParams;
this.props.fetchTimetable(dept, course);
}
当用户导航到route/:dept/:course
时调用它,它工作正常,直到您从/mif/31
导航到/mif/33
,然后按后退按钮。组件实际上没有重新初始化,因此不会调用lifecycle方法,也不会重新加载数据
在这种情况下,是否有某种方式可以重新加载数据?我是否应该使用另一种预加载数据的方法?我看到react路由器在任何位置更改时发出LOCATION\u 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应该重新绘制组件 否则,您可以订阅商店中的更改:
免责声明:我对redux的了解可能比你少 您需要使用
组件willreceiveprops
检查新的道具(nextrops
)是否与现有道具相同(this.props
)。以下是Redux示例中的相关代码:
好的,这是有道理的,我想用这个,但没有进一步研究。我最初不想实现它,因为我认为它每次收到道具时都会重新获取数据,但我没有想到先检查道具。感谢您链接这个示例,我相信它在以后也会非常有用。我已经订阅了存储中的更改,但是存储只有在组件本身获取数据时才会更改。似乎我需要使用componentWillMount和componentWillReceiveProps,因为在初始渲染时不会调用后者。
componentWillReceiveProps(nextProps) {
if (nextProps.dept !== this.props.dept || nextProps.course !== this.props.course) {
dispatch(fetchTimetable(nextProps.dept, nextProps.course))
}
}