2016-09-15 124 views
2

目前笔者从容器组件的生命周期方法componentWillMount API预加载数据:阵营路由器+终极版导航回来不叫componentWillMount

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

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

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

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

免责声明:我大概知道少谈终极版,那么你。

+0

我已经订阅了在店里的变化,但商店的变化,只有当组件本身获取数据。看起来我需要使用componentWillMount和componentWillReceiveProps,因为后者在初始渲染时不会被调用。 –