我在使用 Redux 时遇到了前端问题。后端 API 与 Postman 一起正常工作,所以我知道问题不存在,并且由于某种原因我无法填充 Redux 存储中的数据。
这是我第一次将 userId 传递给后端的 createAsyncThunk,所以我知道问题与此有关。我的后端 API 中有一个 console.log,它会在访问日志时打印日志,以便我可以看到它未被访问。在 Redux 商店中,我收到一条被拒绝的消息,所以我认为这与此有关。
任何人都可以看到我的动作中任何看起来不合适的地方吗?
表单使用效果
const userDiveLog = useSelector(state => state.user.userDiveLog);
useEffect(() => {
dispatch(fetchUserDiveLog(user.userID));
}, []);
createAsyncThunk
export const fetchUserDiveLogs = createAsyncThunk(
'diveLog/requireUserData', // action name
// action expects to be called with the name of the field
async (userId, userDiveLogList) => {
// you need to define a function to fetch the data by field name
const response = await userDiveLogList.fetchById(userId);
const { data } = response;
// what we return will be the action payload
return {
userDiveLog: data,
// items: data
};
},
// only fetch when needed: https://redux-toolkit.js.org/api/createAsyncThunk#canceling-before-execution
{
condition: (userDiveLog, {getState}) => {
const {userDiveLogs} = getState();
// check if there is already data by looking at the array length
if ( userDiveLogs[userDiveLog].length > 0 ) {
// return false to cancel execution
return false;
}
}
}
)
服务
export const userDiveLogList = (userId) => {
return axios.get(API_URL + `userdiveloglist/${userId}`);
};
减速器
export const userSlice = createSlice({
name: 'user',
initialState: {
dives: [],
diveSpots: [],
articles: [],
userDiveLog: []
},
reducers: {
// picks up the pending action from the thunk
[fetchUserDiveLogs.pending.type]: (state) => {
// set didLoadData to prevent unnecessary re-fetching
state.didLoadData = true;
},
// picks up the success action from the thunk
[fetchUserDiveLogs.fulfilled.type]: (state, action) => {
// want to replace all lists, there are multiple ways to do this
// I am returning a new state which overrides any properties
return {
...state,
...action.payload
}
},
答案 0 :(得分:2)
createAsyncThunk
only accepts a single argument for your thunks / payload creation callbacks。您当前声明它需要两个 参数:(userId, userDiveLogList)
。您需要将这两者放在一个对象中。
除此之外,真的没有理由将 userDiveLogList
作为参数传入,除非您过于担心模拟 API 调用(在这种情况下,您可以考虑使用 the "extra argument" option for the thunk middleware 注入 API 层)。我只是在对 createAsyncThunk()
的调用上方声明,或者从另一个文件导入它,然后以这种方式访问它。