繁体   English   中英

如何在 redux 中的 reducer 之间共享 state(如何组织 redux)?

[英]How to share state between reducers in redux (how to organize redux)?

我学会了与 redux 做出反应,但无法理解如何在 reducers 中使用 state 属性 我在/reducers文件夹中创建了 reducers 文件

reducersText.js

export const textReducer = (state = [], action) => {
 switch (action.type) {
     case 'ADD_TEXT':
         return state = action.payload;
     default:
         return state;
 }
}
export const addCustomMinusWordReducer = (state = [], action) => {
 switch (action.type) {
     case 'ADD_CUSTOM_MINUS_WORD':
         return state = action.payload;
     default:
         return state;
 }
}

我在/reducers文件夹中创建了 index.js

import {textReducer, addCustomMinusWordReducer} from "./text"
import {combineReducers} from "redux"

const allReducers = combineReducers({
    text: textReducer,
    customMinusWords: addCustomMinusWordReducer
})

export default allReducers

我的问题是我无法访问在textReducer内的 textReducer 中创建的text addCustomMinusWordReducer 我找到了相关链接,但这不是我要找的。 如何在减速器中使用 state? 谢谢!

来自 redux官方文档。

许多用户后来想尝试在两个 reducer 之间共享数据,但发现 combineReducers 不允许他们这样做。 有几种方法可以使用:

  • 如果 reducer 需要了解 state 的另一个切片中的数据,则可能需要重新组织 state 树形,以便单个 reducer 处理更多数据。

  • 您可能需要编写一些自定义函数来处理其中一些操作。 这可能需要用您自己的顶级减速器 function 替换 combineReducers。您还可以使用诸如 reduce-reducers 之类的实用程序来运行 combineReducers 来处理大多数操作,但也可以为跨越 state 切片的特定操作运行更专业的减速器。

  • redux-thunk 等异步操作创建者可以通过 getState() 访问整个 state。 action creator 可以从 state 中检索额外的数据并将其放入 action 中,以便每个 reducer 都有足够的信息来更新自己的 state 切片。

因此,通过完全使用您的方法而不使用 redux-thunk 并且不使用父减速器重新排序 state。 您可以做的是传入动作创建者的 state。

例如; 一个动作创造者是:

 const ExampleComponent = ({ text, clicked }) => {
    return (
       <button onClick={() => clicked(text)} />
    );
 };

 export default connect(state => ({ 
   text: state.text 
 }, dispatch => ({
   clicked: (textState) => dispatch({ type: 'ADD_CUSTOM_MINUS_WORD', textState })
 })(ExampleComponent);

然后在 reducer 中你可以简单地做;

export const addCustomMinusWordReducer = (state = [], action) => {
 // action.textState will contain the data from textState
 // do something with action.textState
 const { textState } = action;
}

如果您真的想在 reducer 中使用全局 state 就像文档中建议的那样,简单的方法是使用诸如reduce-reducers之类的实用程序。 您可以使用reduceReducers combineReducers 在减速器中, state object 将包含全局 state 而不是 combineReducer 会给出的本地 state。

附言:

正如之前的回答所暗示的那样,在 reducers 内部更改 state 是一个坏主意,这可能会导致难以修复应用程序中的错误。

所以,而不是state = state.payload更好的主意是使用像state = {...state, ...state.payload }这样的扩展运算符,然后 append 会直接将其设置为 7.8 而不是 8827483

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM