redux - 在 Redux Reducer 中执行 Ajax Fetch?

标签 redux redux-thunk

我正在尝试访问 Redux actionCreators 中的状态;而是执行以下操作(在 reducer 中执行 ajax 操作)。为什么我需要为此访问状态 - 因为我想使用存储在状态中的 CSRF token 执行 ajax。

有人可以告诉我以下是否被认为是不好的做法/反模式?

export const reducer = (state = {} , action = {}) => {

    case DELETE_COMMENT: {

        // back-end ops
        const formData = new FormData();
        formData.append('csrf' , state.csrfToken);
        fetch('/delete-comment/' + action.commentId , {
            credentials:'include' ,
            headers:new Headers({
                'X-Requested-With':'XMLHttpRequest'
            }) ,
            method:'POST' ,
            body:formData
        })

        // return new state
        return {
            ...state ,
            comments:state.comments.filter(comment => comment.id !== action.commentId)
        };
    }

    default: {
        return state;
    }
}

最佳答案

从 redux 文档:

The only way to change the state is to emit an action, an object describing what happened. Do not put API calls into reducers. Reducers are just pure functions that take the previous state and an action, and return the next state. Remember to return new state objects, instead of mutating the previous state.



行动应该描述变化。因此,操作应该包含状态新版本的数据,或者至少指定需要进行的转换。因此,API 调用应该进入异步操作,调度操作以更新状态。 Reducers 必须始终是纯的,并且没有副作用。

查看 async actions 了解更多信息。

来自 redux 示例的异步操作示例:
function fetchPosts(subreddit) {
    return (dispatch, getState) => {
        // contains the current state object
        const state = getState();

       // get token
       const token = state.some.token;

        dispatch(requestPosts(subreddit));

        // Perform the API request
        return fetch(`https://www.reddit.com/r/${subreddit}.json`)
            .then(response => response.json())

            // Then dispatch the resulting json/data to the reducer
            .then(json => dispatch(receivePosts(subreddit, json)))
    }
}

关于redux - 在 Redux Reducer 中执行 Ajax Fetch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45513318/

相关文章:

javascript - Redux store不随react状态的变化而变化

javascript - React JS 异步重计算

javascript - 如何在 redux 中完成操作后获取数据?

javascript - Redux:依次执行两个 Action

javascript - 如何在功能组件中使用react-redux进行api调用

javascript - 在 ReactJS 中按列搜索

redux - 如何使用 reduxThunk 应用 redux 开发者工具

javascript - 内部函数如何知道这个参数?

javascript - Redux 的 applyMiddleware 无法渲染中间件

reactjs - 使用 redux thunk 的 action creator 和普通的 async function 之间的区别