【发布时间】:2021-05-21 16:42:23
【问题描述】:
我正在尝试将我的令牌保存在 redux reducer 中。 console.log 工作正常,代码正在运行并且令牌显示出来。
当我尝试将结果保存在变量中时 - 异步代码不会运行,并且变量仍未定义。
这是我的减速器代码:
import { generateCSRF } from '../components/System/CSRF';
const csrfReducer = async (state = null, action) => {
switch(action.type){
case 'CREATE_CSRF_TOKEN':
return (
async () => {
state = await generateCSRF(); // I'm trying to save the returned token in state variable, unsuccesfully.
}
);
default:
return (state);
}
}
export default csrfReducer;
这是我的异步函数:
import { config } from '../../config/global-config';
export const generateCSRF = async () => {
let fetchGetResponse = await fetch(`${config.api_url}csrf`, {
method: 'GET',
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
credentials: "include",
mode: 'cors'
});
let parsedResponse = await fetchGetResponse.json();
console.log(parsedResponse.csrfToken) // this line works.
return parsedResponse.csrfToken;
}
【问题讨论】:
-
你不能有一个异步减速器,这会产生副作用。你想做的事情可以通过 Redux-thunk 或 Redux-sagas 来实现。
标签: reactjs asynchronous redux async-await