reactjs - 有没有办法在 createSlice 中访问全局状态?

标签 reactjs redux redux-toolkit

这是一个例子:

const user = createSlice({
  name: 'user',
  initialState: { name: '', age: 20 },
  reducers: {
    setUserName: (state, action) => {
      state.name = action.payload // mutate the state all you want with immer
    }
  },
  // "map object API"
  extraReducers: {
    [counter.actions.increment]: (state, action) => {
      state.age += 1
    }
  }
})

我可以访问计数器状态吗?
假设我只想在计数器为 30 时增加年龄。否则,我需要在 useEffect 中的计数发生变化时进行监听。钩子(Hook)并调度一些将处理年龄增量(?)的 Action 。

换句话说,根据当前全局状态使用 redux-toolkit 计算状态切片的最佳方法是什么? ?

最佳答案

这在 the Redux FAQ entry on sharing state between reducers 中有介绍.

粘贴关键点:

  • If a reducer needs to know data from another slice of state, the state tree shape may need to be reorganized so that a single reducer is handling more of the data.
  • You may need to write some custom functions for handling some of these actions. This may require replacing combineReducers with your own top-level reducer function. You can also use a utility such as reduce-reducers to run combineReducers to handle most actions, but also run a more specialized reducer for specific actions that cross state slices.
  • Async action creators such as redux-thunk have access to the entire state through getState(). An action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice.

关于reactjs - 有没有办法在 createSlice 中访问全局状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60739372/

相关文章:

javascript - Angular NgRx - 当其他操作返回值时调度一个有效的操作

javascript - Redux:Redux 文档示例的 connect 方法中存在奇怪的解构语法?

reactjs - 如何从 React 组件 Redux Toolkit 中的 createAsyncThunk 获取结果

reactjs - 如何仅为一组特定的注入(inject)端点动态更改我的 RTK 查询 api 的 baseURL?

javascript - 现有应用程序上的 React Native 电影教程的图像未在设备上显示

javascript - React Redux Router 不路由

javascript - 当 Redux 中的 mapToDispatchToProps() 参数时,'dispatch' 不是一个函数

reactjs - 将 props 传递给动态导入的 React 组件

javascript - 如何在 Redux 中使用 reducer 进行多个操作?

typescript - 您正在使用遗留实现。请更新您的代码 : use createWrapper() and wrapper. useWrappedStore()。 nextjs 还原?