[英]Unable to update a particular state using React Reducer
我在我的應用程序上使用 React Context。
這是在我的提供者文件中:
// 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));
}
這是在減速器文件中:
case 'GET_MONITORS':
return {
...state,
monitors: action.payload,
};
我在我的視圖文件中調用它,如下所示:
useEffect(() => {
getMonitors(user.email);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
問題是Reducer沒有更新state,我不明白為什么。 所有其他 Provider 操作都已通過 Reducer 成功更新為 state,而不是這個。
並且, console.log(res.data.monitors);
在 Dispatch 之后的 Provider 文件中,返回預期的響應。
我在這里想念什么?
該代碼工作正常,它也在更新 state。 問題是,我正在從 Chrome 上的 React Devtools 檢查 state,但它沒有顯示更新的 state。
然后我在其中一個視圖文件中控制台記錄特定的 state,它消除了我的疑問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.