【发布时间】:2021-04-05 21:21:57
【问题描述】:
我在使用 Redux 时遇到了前端问题。后端 API 与 Postman 一起正常工作,所以我知道问题不存在,并且由于某种原因,我无法获取 Redux 存储中的数据来填充。
这是我第一次将 userId 传递给后端的 createAsyncThunk,所以我知道问题与此有关。我的后端 API 中有一个 console.log,每当访问它时都会打印日志,这样我就可以看到它没有被访问。在 Redux 商店中,我收到一条被拒绝的消息,所以我认为这与此有关。
任何人都可以看到我的动作中有什么不合适的地方吗?
表单使用效果
const userDiveLog = useSelector(state => state.user.userDiveLog);
useEffect(() => {
dispatch(fetchUserDiveLog(user.userID));
}, []);
创建AsyncThunk
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
}
},
【问题讨论】:
标签: reactjs redux redux-thunk