为什么我们需要在动作创建者本身中向动作创建者发出呼叫?

发布于 2025-01-31 09:46:38 字数 807 浏览 3 评论 0原文

我正在学习有关redux-thunk的知识,在这里不太了解逻辑。如果有人可以解释流程,我会很感激。我要关注的教程会这样做:

//App.js
useEffect(() => {
        dispatch(getPosts());
    }, []);

//actions.js
export const getPosts = () => async (dispatch) => {
    try {
        const { data } = await api.fetchPosts();
        dispatch({ type: 'FETCH_ALL', payload: data });
    } catch (error) {
        console.log(error.message);
    }
};

//reducers.js
export default (posts = [], action) => {
    switch (action.type) {
        case 'FETCH_ALL':
            return action.payload;
        case 'CREATE':
            return [...posts, action.payload];

        default:
            return posts;
    }
};

我们不能在使用效果函数内调用getPosts(),而不是派遣它,因为它会在我们的动作创建者中派遣。如果没有,我们不能只是返回要在行动创建者中派遣的对象而不是派遣它并让第一个调度,然后派遣所述对象。我不确定我在这里想念什么

I'm learning about redux-thunk and don't quite understand the logic here. I'd appreciate if someone could explain the flow. The tutorial I'm following does this:

//App.js
useEffect(() => {
        dispatch(getPosts());
    }, []);

//actions.js
export const getPosts = () => async (dispatch) => {
    try {
        const { data } = await api.fetchPosts();
        dispatch({ type: 'FETCH_ALL', payload: data });
    } catch (error) {
        console.log(error.message);
    }
};

//reducers.js
export default (posts = [], action) => {
    switch (action.type) {
        case 'FETCH_ALL':
            return action.payload;
        case 'CREATE':
            return [...posts, action.payload];

        default:
            return posts;
    }
};

Couldn't we just call getPosts() inside of useEffect func instead of dispatching it since it'll dispatch within our action creator. If not, couldn't we just return the object we wanted to dispatch within our action creator instead of dispatching it and let the first dispatch then dispatch said object. I'm not sure what I'm missing here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文