【问题标题】:Modifying array in redux store修改 redux 存储中的数组
【发布时间】:2017-10-26 15:22:38
【问题描述】:

我正在开发一个基于 react + redux + thunk 的网络应用程序。

我有如下的动作创建者。有 2 个异步 API 调用,首先 fetchUser() 将从服务器获取用户相关信息,然后 fetchUserComments 是另一个异步调用,它返回所有用户 cmets。

export function fetchUserInfoFlow () {
  return (dispatch, getState) => {
    return dispatch(fetchUser()).then(() => {
       return dispatch(fetchUserComments()
    })
  }
}

export function fetchUser() {
  return (dispatch, getState) => {
    return axios.get('urlhere')
      .then(function (response) {
      // basically fetch user data and update the store
      dispatch({type: FETCH_USERS, user:response.data)
      })
      .catch(function (error) {
        console.error(error)
      })
  }
}

export function fetchUserComment() {
  return (dispatch, getState) => {
    return axios.get('urlhere')
      .then(function (response) {

      // fetch user comments, get the user list from store, matching the user id and append the comments list to the user

      let user = {...getState().user}
      response.data.forEach(function (userComment) {
        user.forEach(function (userComment) {
           if(user.userId = userComment.userId){
                user.comments = userComment.comments
            }
        }
      }
      dispatch({type: UPDATE_USER_COMMENT, user:response.data)
      })
      .catch(function (error) {
        console.error(error)
      })
  }
}

我有几个类似于上面的操作创建者获取用户的相关信息并最终更新修改商店的用户列表。

问题是当状态更新时组件没有重新渲染,怀疑我是否在某处改变了用户列表。

我已经阅读了几篇文章,在动作创建者中使用 getSate() 应该只在几种情况下使用,并且不应该更新它的值,因为这会改变状态。

在这种情况下,修改用户列表的逻辑应该放在哪里,如何避免用户列表发生变异?

非常感谢!

【问题讨论】:

    标签: redux redux-thunk


    【解决方案1】:

    这部分应该只进入你的减速器,因为那是你应该对状态进行更改的唯一地方:

      let user = {...getState().user}
      response.data.forEach(function (userComment) {
        user.forEach(function (userComment) {
           if(user.userId = userComment.userId){
                user.comments = userComment.comments //mutating state
            }
        }
      }
    

    【讨论】:

    • 我认为这有点难以决定。假设我必须将上次成功登录添加到用户数组,那么可能我需要在减速器中创建新的 Date()。结果,我的减速器无法正常工作。在我找到更好的解决方案之前,我会暂时听取您的建议,非常感谢。
    • 啊,所以如果你想为客户端最后一次成功登录打上时间戳,你可以使用redux-saga(或你自己编写的中间件)在有效负载中使用 new Date() 调度另一个动作
    • 明白了。感谢您的帮助,将尝试。
    • 很高兴这有帮助
    猜你喜欢
    • 2018-08-10
    • 2020-01-27
    • 2016-12-18
    • 1970-01-01
    • 2019-08-15
    • 2012-08-07
    • 2019-09-25
    • 2017-06-16
    • 2017-07-24
    相关资源
    最近更新 更多