【问题标题】:Updating object inside redux state throws an error在 redux 状态中更新对象会引发错误
【发布时间】:2018-05-03 19:00:37
【问题描述】:

我正在尝试更新减速器中对象内的数组。

const initialState = {
  group: {
    name: "",
    date: "",
    description: "",
    users: [],
    posts: []
  },
  morePosts: false,
  groups: []

};

export function groups(state = initialState, action) {
  switch (action.type) {
    .......
    case REQUEST_MORE_POSTS:
      {
        return {
          ...state,
          group:{
            ...state.group,
            posts: [
              ...state.group.posts,
              ...action.payload.posts
            ]
          },
          morePosts: action.payload.morePosts
        }
      }
    case ADD_NEW_POST:
      {
        return {
          ...state,
          group:{
            ...state.group,
            posts: [
              action.payload,
              ...state.group.posts
            ]
          }
        }
      }
    ........
    default:
      return state;
  }
}

不幸的是,在这两种情况下我都会收到错误:

当我从我的组对象中提取帖子但我需要在里面时,它可以工作。 我无法弄清楚我在这里做错了什么。有人能指出我正确的方向吗?

这是一个用于添加新帖子的动作创建器。

export function addPost(url, payload) {
  return function(dispatch) {
    axios.post(url + "php/addPostGroup.php", {payload}).then(response => {
      dispatch({
        type: ADD_NEW_POST,
        payload: response.data.post
      })
    })
  }
}

response.data.post 是一个简单的对象。

我在调度前添加了 console.log()。这就是我的回复的样子:

【问题讨论】:

  • 在哪种情况下失败了?
  • 在 REQUEST_MORE_POSTS 和 ADD_NEW_POST 上
  • 您能否将每种情况下的操作负载示例添加到您的问题中。
  • 您确定您的响应被解析为 JS 对象而不是字符串吗?
  • 是的,我很肯定

标签: javascript reactjs redux


【解决方案1】:

好的,我解决了。在获取任何数据之前,我的 state.group.posts 数组由于某种原因被视为未定义。我必须使用

手动将其声明为空数组
var posts = state.group.posts != undefined ? state.group.posts:[];

【讨论】:

    猜你喜欢
    • 2020-09-30
    • 2021-06-26
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 2019-05-07
    • 1970-01-01
    • 2018-03-20
    • 2021-12-31
    相关资源
    最近更新 更多