【发布时间】:2022-07-28 19:04:25
【问题描述】:
登录时,我有调用 Redux 操作的初始组件,但在登录用户 token 后发送速度不够快,无法被 axios 标头接收,如果我在 console.log(token) 之前和之后 axios.create({ headers: auth: token })它显示为空,所以我当然会得到“jwt 格式错误”,但是如何设置我的应用程序以在运行 Redux 文件之前等待令牌加载?我在运行 dispatch 之前尝试过检查,以确保存在 token,但该文件甚至在被命中之前就已运行。
// Shoes component
useEffect(() => {
const { sortby } = props;
dispatch(getShoesAsync(sortby)).then((response) => {
setLoading(false);
});
}, [dispatch, props]);
//Redux token auth
const userTokenAxios = axios.create({
baseURL: '/api/shoes',
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
});
// Redux action
export const getShoesAsync = createAsyncThunk(
'shoes/getShoesAsync',
async (payload, { rejectWithValue }) => {
try {
const response = await userTokenAxios.get(`?sortby=${payload}`);
return response.data;
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
【问题讨论】:
标签: javascript reactjs asynchronous redux react-redux