【问题标题】:I am getting this error: actions must be plain objects. Use custom middleware for async actions我收到此错误:操作必须是普通对象。使用自定义中间件进行异步操作
【发布时间】:2019-12-18 01:23:09
【问题描述】:

我收到了错误:

 Actions must be plain objects. Use custom middleware for async actions.

我尝试了以下 Stack Overflow 问题中的解决方案,但没有奏效:
React-Redux: Actions must be plain objects. Use custom middleware for async actions

动作

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);

顺便说一句,我在日志中得到了正确的响应。

【问题讨论】:

    标签: react-native redux react-redux


    【解决方案1】:

    在组件内部,在调用 signupp 函数的地方,你有 ma​​pDispatchToProps 函数作为 react-redux lib 的连接函数中的回调,这在后面类似于 dispatch(signupp()) 的引擎盖(或者你可能在没有 react-redux lib 的情况下直接进行调度)。 根据redux API,这个dispatch函数期望接收一个普通对象,但是你的signupp()函数返回一个promise(因为你里面有async)。

    要解决这个问题,您可以简单地使用redux-thunk 中间件。您还可以在 redux 文档部分看到一些关于 async actions 的示例。

    另一种解决方案是将获取逻辑移至组件,然后仅调度带有您从请求中收到的数据的普通对象。

    【讨论】:

      猜你喜欢
      • 2018-01-30
      • 2018-02-24
      • 1970-01-01
      • 2020-11-05
      • 2019-12-26
      • 2020-11-09
      • 1970-01-01
      • 1970-01-01
      • 2021-11-04
      相关资源
      最近更新 更多