我使用 react-redux
和 @reduxjs/toolkit
进行全局状态管理,在我的商店中,我有 sliceOne
具有初始状态和 reducer 。我试图在带有 useSelector()
的组件中使用状态值,但它显示的是 promise 而不是更新的值。我在该组件中调度操作。
商店/sliceOne.js
import { createSlice } from "@reduxjs/toolkit";
const sliceOne = createSlice({
name: "sliceOne",
initialState: {
firstName: "first",
lastName: "last",
age: 10,
product: {},
},
reducers: {
async action1(state) {
const res = await fetch(`https://fakestoreapi.com/products/2`);
const data = await res.json();
state.product = data;
},
},
});
export const sliceOneActions = sliceOne.actions;
export default sliceOne;
组件
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { sliceOneActions } from "../store/slice-one";
const Compo = () => {
const dispatch = useDispatch();
useEffect(dispatch(sliceOneActions.action1()), []); // without calling this getting state value but with this getting promise
let data = useSelector((state) => state);
console.log(data); //getting promise
return <div></div>;
};
export default Compo;
最佳答案
问题
- Reducer 函数被视为纯粹的同步函数。如果您需要运行一些异步逻辑,那么您需要在异步操作(又名 Thunk)中处理它。
- 该组件通过直接调用
dispatch
代替useEffect
Hook 回调函数,错误地使用了useEffect
Hook 。
解决方案
将异步逻辑从reducer函数移至异步操作。
- 创建 asynchronous Thunk function发出 GET 请求并返回获取的数据。
- 在
sliceOne
切片的extraReducers
中添加一个 case reducer,以处理已完成的action1
操作 Promise。
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
const action1 = createAsyncThunk(
"sliceOne/action1",
async () => {
const res = await fetch("https://fakestoreapi.com/products/2");
const data = await res.json();
return data;
}
);
const sliceOne = createSlice({
name: "sliceOne",
initialState: {
firstName: "first",
lastName: "last",
age: 10,
product: {},
},
extraReducers: builder => {
builder
.addCase((action1.fulfilled, (state, action) => {
state.product = action.payload;
}));
},
});
export const sliceOneActions = {
...sliceOne.actions,
action1,
};
export default sliceOne;
修复 UI 以正确使用 useEffect
Hook 来分派(dispatch) action1
操作。
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { sliceOneActions } from "../store/slice-one";
const Compo = () => {
const dispatch = useDispatch();
useEffect(() => {
dispatch(sliceOneActions.action1());
}), []);
const data = useSelector((state) => state);
...
};
关于javascript - useSelector() 显示了 promise ,而不是来自商店的更新值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74959551/