问题描述
我正在尝试访问 Redux actionCreators 中的状态;而是执行以下操作(在减速器中执行 ajax 操作).为什么我需要为此访问状态 - 因为我想使用存储在状态中的 CSRF 令牌执行 ajax.
I'm trying to wrap my head around accessing the state inside Redux actionCreators; instead did the following (performed ajax operation in the reducer). Why do I need to access the state for this — because I want to perform ajax with a CSRF token stored in the state.
有人可以告诉我以下是否被认为是不好的做法/反模式吗?
Could someone please tell me if the following is considered bad practice/anti-pattern?
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 文档:
From the redux documentation:
改变状态的唯一方法是发出一个动作,一个描述发生了什么的对象.不要将 API 调用放入 reducer.Reducer 只是获取前一个状态和操作并返回下一个状态的纯函数.记住要返回新的状态对象,而不是改变之前的状态.
操作应描述更改.因此,操作应该包含状态新版本的数据,或者至少指定需要进行的转换.因此,API 调用应该进入异步操作,调度操作以更新状态.Reducers 必须始终是纯的,并且没有副作用.
Actions should describe the change. Therefore, the action should contain the data for the new version of the state, or at least specify the transformation that needs to be made. As such, API calls should go into async actions that dispatch action(s) to update the state. Reducers must always be pure, and have no side effects.
查看异步操作了解更多信息.
来自 redux 示例的异步操作示例:
An example of an async action from the redux examples:
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 Reducer 中执行 Ajax Fetch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!