【问题标题】:React: how to update a state property of type array of objectsReact:如何更新对象数组类型的状态属性
【发布时间】:2017-01-04 15:10:10
【问题描述】:

我有以下状态 - 操作历史:

我的问题是我期望一个带有 zoneCategories : Array[8757] 的状态,所以我在减速器中做错了,即:

let setZoneCategoriesReducer = function (zoneCategories = [], action) {
    switch (action.type) {
        case 'SET_CATEGORIES_FROM_SERVER':
            return [
                ...zoneCategories, action.zoneCategories
            ]
        default:
            return zoneCategories;
    }
}

export default setZoneCategoriesReducer

这是我的商店:

import {applyMiddleware, compose, createStore} from 'redux'
import rootReducer from './reducers'
import logger from 'redux-logger'
import thunk from 'redux-thunk'

let finalCreateStore = compose(
    applyMiddleware(thunk, logger())
)(createStore)

export default function configureStore(initialState = {zoneCategories: []}) {
    return finalCreateStore(rootReducer, initialState)
}

这里是我的应用入口点:

import React from 'react';
import App from './App';
import './index.css';
import { Provider } from 'react-redux';
import configureStore from './redux/store'
import { render } from 'react-dom'

let initialState = {
    zoneCategories: []
}

let store = configureStore(initialState)

render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
)

还有,我的根减速器:

import { combineReducers } from 'redux'
import setZoneCategoriesReducer from './setZoneCategoriesReducer'

const rootReducer = combineReducers({
    zoneCategories: setZoneCategoriesReducer
})

export default rootReducer

我现在精神障碍,有什么帮助吗?

【问题讨论】:

    标签: reactjs ecmascript-6 redux


    【解决方案1】:

    在您的setZoneCategoriesReducer 函数中,您添加action.zoneCategories 作为返回状态的一个元素,它大概包含您实际需要的8757 个元素。传播而不是直接添加。

    let setZoneCategoriesReducer = function (zoneCategories = [], action) {
    // ...
            return [
                ...zoneCategories, ...action.zoneCategories
            ]
    // ...
    }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-07-01
      • 2021-05-28
      • 1970-01-01
      • 2021-06-04
      • 2019-04-28
      • 1970-01-01
      • 2016-10-06
      • 2023-01-31
      相关资源
      最近更新 更多