reactjs - 与 useContext 一起使用时,Usereducer 状态始终未定义
问题描述
我正在尝试将 useReduce 与 一起使用useContext
,当我在减速器中控制台值时,我在控制台中获取了一个对象数组,但是当我尝试从另一个组件访问状态时,我得到的状态是未定义的。State.map() 完全是空的。
这是我的代码
应用程序.js
import React, { createContext, useReducer, useEffect } from 'react';
import Uploadproject from './Uploadproject';
import Getprojects, { projectget } from './Getprojects';
import reducer from './reducer/Usereducer';
export const Contextstate = createContext();
const App = () => {
const initialvalue = null;
const [state, dispatch] = useReducer(reducer, initialvalue);
const updatestate = async () => {
const data = await projectget();
dispatch({ type: 'add', payload: 'from app.js' });
};
useEffect(() => {
updatestate();
}, []);
return (
<>
<Contextstate.Provider value={{ state, dispatch }}>
<Uploadproject />
<Getprojects />
</Contextstate.Provider>
</>
);
};
export default App;
Usereducer.js
import { projectget } from '../Getprojects';
const reducer = (state, action) => {
if (action.type === 'add') {
projectget().then((result) => {
console.log(result);
// state = [ ...result]
state = result;
console.log(state);
return state;
});
}
};
export default reducer;
获取项目.js
import React, { useContext, useEffect, useState } from 'react';
import { Contextstate } from './App';
const Getprojects = () => {
const { state, dispatch } = useContext(Contextstate);
const getstate = () => {
dispatch({ type: 'add', payload: 'from getprojects' });
};
useEffect(() => {
getstate();
}, []);
console.log(state);
return (
<>
<div>
<h1>Projects</h1>
{state &&
state.map((cur) => {
return (
<div key={cur._id}>
<h1>{cur.title}</h1>
<p>{cur.description}</p>
<button
onClick={() => {
deletproject(cur._id);
}}
>
Delete
</button>
</div>
);
})}
</div>
</>
);
};
export default Getprojects;
当我尝试从 Getprojects 组件访问状态时,它的值是未定义的。但是如果我在减速器内部,控制台会得到一个对象数组。在任何其他组件中,状态是未定义的。任何想法???
解决方案
如果你想使用 redux 在你的应用程序中处理异步逻辑,你应该选择一个Async Redux Middleware
包
- redux-thunk(更容易配置,适合小型项目)
- 还原传奇
- redux-observable 等
或者您可以只使用useEffect
并仅向其发送结果操作。例如:
useEffect(() => {
dispatch(getProjectActionStart());
projectget()
.then((result) => {
console.log(result);
// state = [ ...result]
state = result;
console.log(state);
dispatch(getProjectActionStart(state));
return state;
})
.catch(() => {
dispatch(getProjectActionFailed());
});
}, []);
推荐阅读
- python - Target_size image_gen.flow_from_dataframe InceptionResNetV2 (Keras) 用于较小的图像
- xcode - Xcode 如何计算故事板的部署目标?
- asynchronous - 如何在 python3.7 的 asyncio 库中运行时将任务添加到事件循环?
- node.js - AWS Lambda ERR_STREAM_WRITE_AFTER_END 上的 Node.js mysql2
- flutter - 如何在颤动中更改 DrawerHeader 的高度?
- ruby-on-rails - 如何通过浏览器历史实现“返回”的链接?
- java - 将函数累积应用于任何类型列表中的每个元素
- python - Python Bot 在 Whatsapp 上回复你好
- javascript - 反应原生的条件显示
- javascript - ctx.fillrect 不起作用