因此,createStore()Redux 现已弃用,并由@reduxjs/toolkitconfigureStore()推荐。
我很确定这与无法在我的操作中userInfo使用状态有关getState()。
getState()的userLogin回报undefined。但是当我删除 时getState(),该操作就起作用了。
店铺:
import { configureStore } from '@reduxjs/toolkit'
import thunk from 'redux-thunk'
import {
productAddReducer,
productDeleteReducer,
productDetailsReducer,
productListReducer,
productUpdateReducer,
} from './reducers/productReducers'
import { composeWithDevTools } from 'redux-devtools-extension'
import {
userLoginReducer,
userRegisterReducer,
userDetailsReducer,
userListReducer,
userDeleteReducer,
userUpdateReducer,
} from './reducers/userReducers'
const reducer = {
// User
userLogin: userLoginReducer,
userRegister: userRegisterReducer,
userDetails: userDetailsReducer,
userList: userListReducer,
userDelete: userDeleteReducer,
userUpdate: userUpdateReducer,
// Product
productAdd: …Run Code Online (Sandbox Code Playgroud) 我正在尝试将我正在构建的应用程序切换为使用 Redux Toolkit,并且在我从 createStore 切换到 configureStore 时注意到出现此错误:
A non-serializable value was detected in the state, in the path: `varietals.red.0`. Value:, Varietal {
"color": "red",
"id": "2ada6486-b0b5-520e-b6ac-b91da6f1b901",
"isCommon": true,
"isSelected": false,
"varietal": "bordeaux blend",
},
Take a look at the reducer(s) handling this action type: TOGGLE_VARIETAL.
(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)
Run Code Online (Sandbox Code Playgroud)
在四处探索之后,我发现问题似乎出在我的自定义模型上。例如,品种数组是从品种模型创建的:
class Varietal {
constructor(id, color, varietal, isSelected, isCommon) {
this.id = id;
this.color = color;
this.varietal = varietal;
this.isSelected = isSelected;
this.isCommon = isCommon;
}
}
Run Code Online (Sandbox Code Playgroud)
并使用它映射一个字符串数组来创建我的 Varietal 数组,该数组进入我的状态:
// my utility …Run Code Online (Sandbox Code Playgroud) 我的问题是我应该使用哪个?Redux Toolkit 可以替代 Redux 核心吗?
商店.ts
export const store = configureStore({
reducer: {
auth: authReducer
},
middleware: [],
});
export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
Run Code Online (Sandbox Code Playgroud)
钩子.ts
export const useAppDispatch = () => useDispatch<AppDispatch>();
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector;
Run Code Online (Sandbox Code Playgroud)
authSlice.ts(导致问题的函数)
export const fetchUser = createAsyncThunk(
'users/fetchByTok',
async () => {
const res = await getUser();
return res.data;
}
)
Run Code Online (Sandbox Code Playgroud)
授权ts
const Auth = ({ component, isLogged }: {component: any, isLogged: boolean}) => {
const dispatch = useAppDispatch();
useEffect(() => …Run Code Online (Sandbox Code Playgroud) 在我的 Redux 存储中,我有多个切片,我想访问langspeciesSlice 内的settingsSlice 的状态。
这是我的切片的代码示例:
const settingsSlice = createSlice({
name: 'settings',
initialState: { lang: 'en', theme: 'dark' },
reducers: {
...
},
});
const speciesSlice = createSlice({
name: 'species',
initialState: data[`vds-list-${HERE I WANT TO USE THE "lang" STATE OF THE SETTINGSSLICE}`],
reducers: {
...
},
});
Run Code Online (Sandbox Code Playgroud)
到目前为止我还没有找到解决方案,所以也许这是不可能的?
我可以只使用一个切片,其中包含所有状态,但我真的很想将状态的不同部分分隔在不同的切片中。
所以我是 redux-toolkit 的新手,我想做一些非常简单的事情。我想通过这个辅助函数在 POST 请求上发送一些数据。所以我尝试了这个
export const submitPaymentToServer = createAsyncThunk(
'data/fetchAll',
async ({ name, data }) => {
return fetch('/payments', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name,
data,
}),
})
.then((res) => res.json())
.then((res) => res)
},
)
Run Code Online (Sandbox Code Playgroud)
但当我这样称呼它时
dispatch(
submitPaymentToServer({
name,
data,
}),
)
Run Code Online (Sandbox Code Playgroud)
typescript 抱怨说我没有正确数量的参数。那么我该如何将参数传递给这个函数呢?或者使用工具包执行此操作的方法是什么?
==================== TLDR ==========================
@markerikson(请参阅已接受的答案)亲切地指出了当前的解决方案和未来的解决方案。
编辑:2020 年 11 月 15 日:链接到文档以在 Slice 中使用 Async Thunk
RTK确实支持使用 thunk 中间件的 reducer 中的 thunk(参见答案)。
在 1.3.0 版本(目前 alpha 于 2020 年 2 月)中,有一个辅助方法createAsyncThunk() createAsyncThunk将提供一些有用的功能(即根据 Promise的状态触发 3 个“扩展”reducer)。
========================原始帖子 2020 年 2 月====================== ====
我对 Redux 很陌生,遇到了 Redux Toolkit (RTK) 并希望实现它提供的更多功能(或者在这种情况下可能没有?)(2020 年 2 月)
我的应用程序分派到通过创建的减速器切片createSlice({})(请参阅createSlice api docs)
到目前为止,这非常有效。我可以轻松地使用内置dispatch(action)和useSelector(selector)调度动作,并在我的组件中很好地接收/响应状态变化。
我想使用 axios 的异步调用从 API …
我已经使用 Axios 成功编写了我的应用程序来获取内容。截至目前,它已设置为在发生某些事件时获取内容(例如单击提交按钮)。但是,我正在尝试Redux 的 RTK 查询解决方案。该包生成挂钩,并在其示例中提供了在挂载时调用挂钩的简单组件级示例。
我如何利用这些 rtk-hook(以及一般的钩子),以便将它们与 、 和条件事件等行为联系onClick起来onSubmit?我知道这与hooks 规则准则相冲突,但我无法想象 RTK-Query 会受到如此限制,只允许组件级 onMount API 调用。
当我试图解决这个问题/等待一个有用的例子时,我正在阅读一些相关文章:
第二篇文章似乎有些相关,但我觉得它偏离了道路太远,并且正在质疑它是否值得rtk-query安装。我不妨只使用它axios,因为它可以在我的组件和逻辑中的任何地方使用。有人可以教育我如何解决这个问题吗?我是 rtk-query 的新手,它看起来真的很酷,但它的实现方法似乎也确实受到限制。
api.ts:import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
const apiEndpoint = 'http://localhost:5000';
export const myApi = createApi({
reducerPath: 'myApi',
baseQuery: fetchBaseQuery({ baseUrl: apiEndpoint }),
endpoints: builder => ({
getFileById: builder.query<any, { id: string; fileId: string }>({
query: arg => { …Run Code Online (Sandbox Code Playgroud) 我需要将当前状态重置为初始状态。但我所有的尝试都没有成功。我如何使用 redux-toolkit 做到这一点?
const showOnReviewSlice = createSlice({
name: 'showOnReview',
initialState: {
returned: [],
},
reducers: {
reset(state) {
//here I need to reset state of current slice
},
},
});
Run Code Online (Sandbox Code Playgroud) 以下代码使用 RTK 查询创建 Redux Hook:
export const specialtiesApi = createApi({
reducerPath: 'specialtiesApi',
baseQuery: fetchBaseQuery({ baseUrl: 'https://someplace.com/' }),
endpoints: (builder) => ({
getSpecialties: builder.query({
query: (name) => `specialties`,
}),
}),
});
export const { useGetSpecialtiesQuery } = specialtiesApi;
Run Code Online (Sandbox Code Playgroud)
最后一行代码抛出 Typescript 编译时错误:
Property 'useGetSpecialtiesQuery' does not exist on type 'Api<BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryError, {}, FetchBaseQueryMeta>, { getSpecialties: QueryDefinition<...>; }, "specialtiesApi", never, unique symbol>'
Run Code Online (Sandbox Code Playgroud)
我的代码改编自https://redux-toolkit.js.org/rtk-query/usage-with-typescript使用 Typescript 4.3.5。
我看不出有什么问题。有任何想法吗?
redux-toolkit ×10
redux ×8
reactjs ×6
javascript ×4
react-redux ×4
redux-thunk ×2
rtk-query ×2
react-hooks ×1
redux-saga ×1
typescript ×1