假设我的 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/