使用 userID 参数创建 createAsyncThunk

Creating a createAsyncThunk with userID argument

我在使用 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
            }
        },

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() 的调用之上声明它,或者从另一个文件导入它,然后以这种方式访问​​它。