gpt4 book ai didi

redux - 在 Redux Reducer 中执行 Ajax Fetch?

转载 作者:行者123 更新时间:2023-12-01 07:51:57 25 4
gpt4 key购买 nike

我正在尝试访问 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com