gpt4 book ai didi

javascript - redux - reducer 状态为空

转载 作者:数据小太阳 更新时间:2023-10-29 04:38:21 25 4
gpt4 key购买 nike

我正在尝试在 redux docs' basic example 中复制类似于 TodoList 示例的内容.第二个 reducer 接收一个数组 - styleItems = [{... ... }, {... ...}] - 然后调用第一个函数来作用于每个单独的对象.

我通过以下方式向应用程序容器提供了一个 initialState,如 containers/app.js 所示。但是,传递给 styleItems reducer 的状态似乎每次都是空白数组。

但是,react 会根据初始配置呈现 UI,并且 react dev-tools 会按预期显示状态结构。 redux store 是否以某种方式看到与 react 相同的东西?

containers/app.js

function starterInfo(state) {
return {

// The ID of this particular object
id: 12345,

// Various keys and theri css values
styleItems: [
{
pk: 31,
order: 1,
label: 'Caption text color',
css_identifier: '.caption-text',
css_attribute: 'color',
css_value: '#FFFFFF'
},
{
pk:23,
order: 2,
label: 'Caption link color',
css_identifier: '.caption-link',
css_attribute: 'color',
css_value: '#FEFEFE'
}
],

// Network state info
currently_fetching: false,
currently_posting: false
}
}

export default connect(starterInfo)(App)

reducers/index.js

// This handles a single styleItem object within the array
function change_css(state = {}, action){
switch (action.type){
case actions.CHANGE_CSS:

if (state.order !== action.order){
return state
}

return {
...state,
css_value
}

default:
return state
}
}

// This handles the styles array in the global state
function styleItems(state = [], action){
switch(action.type){
case actions.CHANGE_CSS:

const foobar = state.map(styleItem =>
change_css(styleItem, action)
)

return foobar

default:
return state
}
}

最佳答案

简短的回答是您没有完全正确地通过初始状态。 React Redux 绑定(bind)的 connect 函数的第一个参数是 mapStateToProps。此函数的要点是获取您的应用程序中已经存在的状态,并将其映射到组件的 props。您在 starterInfo 函数中所做的只是对组件的状态进行硬编码。因为你返回的是一个普通对象,React 并不知道其中的区别,所以它工作得很好,但 Redux 还不知道你的应用程序状态。

相反,您应该做的是直接向 reducer 提供初始状态,如下所示:

const intialStyleItemsState = [
{
pk: 31,
order: 1,
label: 'Caption text color',
css_identifier: '.caption-text',
css_attribute: 'color',
css_value: '#FFFFFF'
},
{
pk:23,
order: 2,
label: 'Caption link color',
css_identifier: '.caption-link',
css_attribute: 'color',
css_value: '#FEFEFE'
}
];

function styleItems(state = intialStyleItemsState, action){ ...

最终,因为您要拆分 reducer,您需要使用 Redux 的 combineReducers 实用程序将它们重新组合在一起,将根 reducer 提供给您的商店并从那里开始。

关于javascript - redux - reducer 状态为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34859614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com