【问题标题】:how can I access state from another slice with redux toolkit我如何使用 redux 工具包从另一个切片访问状态
【发布时间】:2022-12-31 12:43:27
【问题描述】:

我有多个切片,我想从另一个切片中的切片访问状态,那么我该如何访问状态来自 filterSlice 中的 productsSlice

产品切片

我想访问产品状态从这片

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  products: ["data"], // i want to access products in filterSlice 
};

export const productsSlice = createSlice({
  name: "products",
  initialState,
  reducers: {},
});

过滤切片

将产品状态添加到过滤产品

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  filteredProduct: [// access products from proudctsSlice ],
}

export const filterSlice = createSlice({
  name : "filter",
  initialState,
  reducers: {  }
})

【问题讨论】:

  • 使用 thunk Api redux-toolkit.js.org/api/createAsyncThunk 第二个参数 thunkAPI 将有一个方法 getState 来获取所有状态..或将其他状态值作为有效负载传递..我建议您以所有相关数据都在一个切片中的方式重新组织您的商店
  • 过滤后的数据很可能一开始就不应该成为您商店的一部分——通常是派生数据。见redux.js.org/recipes/computing-derived-data

标签: reactjs redux react-redux redux-toolkit


【解决方案1】:

两个可能的方向给你 -

  1. Reducer 只能访问它们所属的切片的状态,我认为您应该保持这种状态。所以可能会尝试以一种您不必在切片之间进行状态共享的方式重新设计它。

    请查看此常见问题解答问题"how can I share state between reducers?" 了解更多详细信息。

    1. 如果您仍然想继续,那么您可以尝试将商店本身导入目标模块并执行const reduxStore = store.getState();。你可以访问任何你想要的东西:)

【讨论】:

  • 2. 将不起作用 - Redux 在执行 reducer 时阻止 getState 调用,这是有充分理由的。
  • 我认为最明智的解决方案是在分派动作时在动作有效负载中传递所需的信息。例如- dispatch(someAction(payloadObj)) 在这里您将使用来自另一个切片的所需状态/数据填充 payloadObj。
【解决方案2】:

谁能帮我解决我被困了两天

这是我的 thunk 函数

export const BigHitsPlaylistAsync = createAsyncThunk
{state:Rootstate}    
(
        'BigHits',
        async (_,getState) => {
            try {
                const token =  getState().AccessToken.token    
                // const  {token}  =  useSelector((state) => {
                    // return state
                // })
                const endPointUrl = `https://api.spotify.com/v1/me/top/artists?time_range=medium_term&limit=10&offset=5`;
                const res = await fetch(endPointUrl, {
                    'headers': {
                        'Authorization': 'Bearer ' + token
                    },
                    json: true
                })
                const Data2 = await res.playlists;
                // setResponse(Data.playlists)
                console.log(token);
                return token
                
            } catch (error) {
                console.log(error);
            }
        }
    )

    and my slice function is 

const HomeScreenApiSlice = createSlice({
    name: 'HomeScreen',
    initialState,
    // reducers: {},
    extraReducers: (builder) => {
        builder.addCase(BigHitsPlaylistAsync.fulfilled, (state, action) => {
            state.BigHits = action.payload
        })
    },
})

【讨论】:

    猜你喜欢
    • 2020-10-08
    • 2021-11-21
    • 1970-01-01
    • 2022-12-11
    • 1970-01-01
    • 2017-04-02
    • 1970-01-01
    • 2021-09-15
    • 2023-01-31
    相关资源
    最近更新 更多