javascript - 为什么我的 redux 存储将属性映射到具有单个属性和值的对象?

标签 javascript reactjs react-redux

假设我的 redux 存储状态是 {posts: []} 在我的 reducer 中,我返回 {posts: [1, 2, 3] 然后 redux 告诉我存储状态是 {posts: {posts: [1, 2, 3]}}

这是一个带有我的简单操作代码的实际示例

export const GET_POSTS = 'GET_POSTS'

export function getPosts ( posts ) {
  // posts = Array of objects right here

  return {
    type: GET_POSTS,
    posts
  }
}

(类别的单独文件)

export const GET_CATEGORIES = 'GET_CATEGORIES'

export function getCategories ( categories ) {
  // categories = Array of objects right here

  return {
    type: GET_CATEGORIES,
    categories
  }
}

..和 reducer 代码

import { GET_POSTS } from './actions'

function posts (state = {}, action) {
  const { posts } = action
  // posts = Array of objects right here

  switch(action.type) {
    case GET_POSTS :
      return {
        ...state,
        posts
      }
    default :
      return state
  }
}

export default posts

(类别的单独文件)

import { GET_CATEGORIES } from './actions'

function categories (state = {}, action) {
  const { categories } = action
  // categories = Array of objects right here

  switch(action.type) {
    case GET_CATEGORIES :
      return {
        ...state,
        categories
      }
    default :
      return state
  }
}

export default categories

结合在appReducer.js

import categories from './Categories/reducer';
import posts from './Posts/reducer';
import { combineReducers } from 'redux';

export default combineReducers({
  categories,
  posts
})

出于某种原因,在减少状态后,我必须这样做才能获取我的数组

function mapStateToProps ({ posts, categories }) {
  // posts and categories no longer arrays. each are an object with a single property that is the array
  posts = posts.posts ? posts.posts : []
  categories = categories.categories ? categories.categories : []

  return {
    posts,
    categories
  }
}

最佳答案

combineReducers将 reducer 映射到您的状态,并且仅将与 reducer 名称匹配的状态切片传递到 reducer 中。这意味着传递到 postsReducer 的状态切片是 state.posts。因此,您的 reducer 应该返回一系列帖子,而不是完整状态。

function posts (state = [], action) {
  const { posts } = action
  // posts = Array of objects right here

  switch(action.type) {
    case GET_POSTS :
      return posts;
    default :
      return state;
  }
}

关于javascript - 为什么我的 redux 存储将属性映射到具有单个属性和值的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46636256/

相关文章:

javascript - Firefox 插件 : HTTP Log that saves to text file with time, 用户名、计算机名未创建文本文件

javascript - 将函数调用存储在数组中

javascript - 路由渲染后,将 JavaScript 应用于 React 中的布局

javascript - 状态使用身份验证

javascript - Redux - 商店不起作用

reactjs - 填充 redux 存储后,React 组件未更新

javascript - 如何检查数组是否是 Javascript 中的空数组的数组

javascript - 在 html 页面中以有序的方式显示结果

reactjs - 在 redux-saga 或 reducer 中处理下载项标准化?

reactjs - React Router 在重新加载时起作用,但在单击链接时不起作用