【问题标题】:React/Redux ComponentWillMount isn't loading dataReact/Redux ComponentWillMount 没有加载数据
【发布时间】:2018-04-12 02:51:59
【问题描述】:

使用带有 Redux 状态的基于 React 的应用程序,我有一个组件应该在加载时从后端加载数据列表。

我已经加载了组件,并映射了状态和操作。我在这里有组件的主要数据调用:

componentWillMount(){
    this.props.loadTasks(this.props.user);
}

在此处触发动作函数:

export const loadTaskList = (user) => {
  return (dispatch) => {
    fetch(`http://localhost:3201/tasks/${user._id}`)
        .then(res => res.json())
        .then(tasks => {
          console.dir(tasks);
          return({type: LOAD_TASKS, payload: tasks});
        });
  }
}

它被发送到reducer,并像这样合并到商店中:

export default (state=initState, {type, payload}) => {
  switch (type) {
    case LOAD_TASKS:
      console.log(`Payload of tasks: ${payload}`);
      return{...state, tasks: payload};
    default:
      return state;
  }
}

问题是为什么这没有进入我的状态,因此没有进入我的组件?

编辑:为了清楚起见,我的 mapState 和 mapActions 对象:

let mapState = (state) => ({
  tasks: state.tasklist,
  user: state.user
});

let mapActions = (dispatch) => ({
  loadTasks: loadTaskList, //taskList Reducer
  selectTask: selectTask, //ActiveTask Reducer
  deleteTask: deleteTask, //TaskList Reducer
  newTask: newTask //activeTask Reducer
});

【问题讨论】:

  • 我认为您需要将任务分配给组件中的某些内容。目前看起来您的 this.props.loadTasks 没有对生成的有效负载做任何事情,因此它不会修改组件的状态/道具。
  • store中的tasks对象连接到mapstate()中的组件

标签: reactjs redux react-redux


【解决方案1】:

因为你没有发送action,所以使用这个:

dispatch({type: LOAD_TASKS, payload: tasks});

代替:

return({type: LOAD_TASKS, payload: tasks});

Return 不会做任何事情。

【讨论】:

  • 啊...derp...是的,还是习惯了redux
  • 面临问题..?
  • 抱歉,这只是我在忘记某些事情时畏缩不前。仍然有点偏离,但此时它处于减速器和连接功能。它会完成的。
  • 我觉得应该是let mapActions = (dispatch) => ({ loadTasks: (user) => dispatch(loadTaskList(user), });
【解决方案2】:

UNSAFE_componentWillMount() 在挂载之前被调用。它在 render() 之前调用,因此在该方法中同步调用 setState() 不会触发额外的渲染。通常,我们建议使用 constructor() 来初始化状态。

我会推荐相同的方法或在 componentDidMount() {} 中调用 loadTasks() 而不是 componentWillMount()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-25
    • 2016-10-06
    • 2017-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    相关资源
    最近更新 更多