【问题标题】:React router + redux navigating back doesn't call componentWillMountReact 路由器 + redux 导航返回不会调用 componentWillMount
【发布时间】:2017-01-23 16:25:25
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    免责声明:我对 redux 的了解可能比你少。

    【讨论】:

    • 我已经订阅了store里面的改动,但是store只有在组件本身取数据的时候才会改动。看来我需要使用 componentWillMount AND componentWillReceiveProps,因为后者在初始渲染时不会被调用。
    【解决方案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))
      }
    }
    

    【讨论】:

    • 好吧,有道理,我在考虑使用它,但没有进一步研究。我最初并不想实现这个,因为我认为它每次收到道具时都会重新获取数据,但我没有想到先检查道具。感谢您链接示例,我相信它稍后也会非常有用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    • 2018-09-04
    • 1970-01-01
    • 2016-10-10
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多