【发布时间】:2020-06-30 18:05:04
【问题描述】:
我在我的应用程序上使用 React Context。
这是在我的 Provider 文件中:
// Initial State
const initialState = {
user: [],
monitors: '',
loading: true,
isAuthenticated: false,
};
function getMonitors(username) {
axios
.get(`/api/users/usermonitors/?user=${username}`)
.then((res) => {
dispatch({
type: 'GET_MONITORS',
payload: res.data.monitors,
});
console.log(res.data.monitors); // This returns expected response
})
.catch((err) => console.log(err));
}
这在 Reducer 文件中:
case 'GET_MONITORS':
return {
...state,
monitors: action.payload,
};
我在我的视图文件中调用它如下:
useEffect(() => {
getMonitors(user.email);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
问题是 Reducer 没有更新状态,我不明白为什么。所有其他 Provider 操作都被 Reducer 成功更新为 state,但不是这个。
并且,在 Dispatch 之后的 Provider 文件中的 console.log(res.data.monitors); 返回预期的响应。
我在这里缺少什么?
【问题讨论】:
标签: javascript reactjs react-context