react-native - 我收到此错误:操作必须是普通对象。使用自定义中间件进行异步操作
问题描述
我收到错误:
Actions must be plain objects. Use custom middleware for async actions.
我已经尝试了以下 Stack Overflow 问题中的解决方案,但没有奏效:
React-Redux: Actions must be plain objects。使用自定义中间件进行异步操作
行动
export async function signupp(data){
console.log('In signupp:');
try{
const request = await axios({
method:'POST',
url:'http://192.168.1.10:3003/users/signup',
data:{
email:data.email,
password:data.password
},
}).then(response=>{
console.log(response.data);
return response.data
}).catch( e => {
console.log(e);
return false
});
return {
type:'signup',
payload:request
}
}
catch(e) {
console.log(e);
return false;
}
}
减速器
export default function(state={},action){
switch(action.type){
case 'signup':
return {
...state,
auth:{
email: action.payload.email,
password:action.payload.password
}
}
}
}
店铺
const createStoreWithMiddleware = applyMiddleware()(createStore);
const appRedux = () => (
<Provider store = {createStoreWithMiddleware(reducers)}>
<App/>
</Provider>
)
AppRegistry.registerComponent(appName, () => appRedux);
顺便说一句,我在日志中得到了正确的响应。
解决方案
在组件内部,在您调用signupp函数的地方,您有mapDispatchToProps函数作为 react-redux lib 的 connect 函数中的回调,它在幕后执行诸如dispatch(signupp()) 之类的操作(或者您可能正在执行 dispatch直接没有 react-redux lib)。根据 redux API,这个 dispatch 函数期望接收一个普通对象,但是你的 signupp() 函数返回一个 promise(因为你有 async 里面)。
要解决这个问题,你可以简单地使用redux-thunk中间件。您还可以在 redux 文档部分中看到一些关于异步操作的示例。
另一种解决方案可能是将获取逻辑移动到组件,然后仅发送带有从请求中收到的数据的普通对象。
推荐阅读
- artificial-intelligence - 如何区分从左到右和从右到左的 alpha-beta 修剪?
- angular - 在 Angular 9 中使用查询参数导航到 url
- haskell - 为什么这个的第二个版本在指数时间内运行?
- android - 导航组件可以在活动之间使用吗?
- typescript - Typescript 解构对象和对象的内部属性
- sql - Power BI 中没有周六和周日的上一个日期
- r - 如何在使用 pivot_wider() 后保留原始变量,而无需手动创建临时变量来传播数据?
- java - 如何验证从 yaml 文件开始的输入字段
- amazon-web-services - 应该用作 Runner Manager 并生成新机器的 EC2 实例正在运行管道作业
- node.js - 无法连接到 node.js API、EC2 AWS [已解决]