【发布时间】:2021-08-10 05:13:35
【问题描述】:
在我通过 Thunk 操作传递参数的情况下,我的 Redux 存储出现问题。如果没有参数,我的商店会正确填充。该操作已成功完成,我可以看到我的操作的成功/已完成消息已将数据返回到前端,但没有迹象表明它作为状态进入商店。
我之前有一个实例,其中数组列表从后端错误地命名,但这次不是这种情况。
我的商店没有填充状态数据的原因有哪些?
动作
export const requireUserDiveLogData = createAsyncThunk(
'users/requireData', // action name
// action expects to be called with the name of the field
async (userId) => {
// you need to define a function to fetch the data by field name
const response = await userDiveLogList(userId);
// what we return will be the action payload
return response.data;
},
// only fetch when needed: https://redux-toolkit.js.org/api/createAsyncThunk#canceling-before-execution
{
// _ denotes variables that aren't used - the first argument is the args of the action creator
condition: (_, { getState }) => {
const { users } = getState(); // returns redux state
// check if there is already data by looking at the didLoadData property
if (users.didLoadDiveLogData) {
// return false to cancel execution
return false;
}
}
}
)
减速器
export const userSlice = createSlice({
name: 'users',
initialState: {
userDiveLogList: [],
didLoadDiveLogData: false,
},
reducers: {
[requireUserDiveLogData.pending.type]: (state) => {
state.didLoadDiveLogData = true;
},
[requireUserDiveLogData.fulfilled.type]: (state, action) => {
return {
...state,
...action.payload
}
},
}
})
【问题讨论】:
-
不明白您的问题?你想做什么?你期待什么结果?
-
我正在尝试将状态添加到商店,以便我可以访问它。我可以看到操作负载正在成功,但状态没有填充到用户字段中。
标签: javascript reactjs redux react-redux redux-toolkit