【问题标题】:Actions must be plain objects. Use custom middleware for async actions React-Redux动作必须是普通对象。使用自定义中间件进行异步操作 React-Redux
【发布时间】:2018-11-12 20:22:54
【问题描述】:

我绝对是 React Native、Redux 和朋友的初学者。
现在我尝试使用 React Native 和 Redux 创建一个应用程序。
在这个过程中我发现了这个错误:

我尝试像这样在我的应用程序中使用 Redux:

export const confirmRegister = (userdata) => {
    return (dispatch) => {
        return(
            fetch(URI + path, {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    'x-application-id' : AppId,
                    'hashing' : this.generateHashing(userdata)
                },
                body: userdata,
            })
            .then((response) => {
                return response.json()
            })
            .then((response)=>{
                dispatch(setDataAfterRegister(response.result))
            })
            .catch(error => {alert(error)})
        )
      };
    };

    export function setDataAfterRegister(data){
      return{
        type:'REGISTERED',
        name:data.name,
        token:data.access_token
      }
    }

我还在学习如何使用 Redux。
任何帮助将不胜感激。


这是我的商店:

import { createStore } from 'redux';
import rootReducer from './reducers';
 
let store = createStore(rootReducer);
 
export default store;

【问题讨论】:

  • 你设置 redux-thunk 了吗?
  • 不,我的应用中没有 redux-thunk
  • 展示你如何创建你的 redux 存储。

标签: reactjs react-native redux


【解决方案1】:

confirmRegister函数返回一个函数:

export const confirmRegister = (userdata) => {
  return (dispatch) => {

Redux 不知道如何在本地处理它。你需要一个中间件来做到这一点。最流行的中间件是redux-thunk

首先安装它:

npm install --save redux-thunk

然后设置中间件:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

【讨论】:

  • 非常感谢,你救了我 :D... 再来一个,我如何捕捉更新的状态?
  • @kurniawan26 没问题。如果您想访问当前状态,请使用 react-redux 和 connect
  • 它有效,现在我想在状态更新后将navigate 转到主屏幕,当我在主屏幕上时我得到了这个warningWarning:Cannot update during an existing state transition 任何想法?
  • @kurniawan26 你可能尝试更新卸载的组件。
  • 对不起,先生,我不明白你的意思..这是我真的需要解决的问题吗?或者我可以忽略warning
【解决方案2】:

你的 Action creator confirmRegister 返回一个函数,但在 React 中 action creator 返回一个普通 JS 对象的 action。

所以你需要一些中间件来告诉 react 这个异步调用。 可以使用Redux-thunkredux-Sagas等中间件。 这将使您的动作创建者返回一个函数,并且该函数在获得响应时将分派一个新的动作对象。

您可以使用npmyarn 安装中间件

npm install --save redux-thunk
yarn add redux-thunk

将其添加到您的商店配置文件中。

为此Warning:Cannot update during an existing state transition 您必须在ComponentWillReceivePropsComponentWillMount 中设置组件的状态。您可能正在render 方法中设置状态。 `

【讨论】:

  • 我应该在哪里打电话给ComponentWillReceiveProps?它是在我当前的屏幕上还是在我要导航到的屏幕上?
  • 您希望从中进行导航的当前屏幕
  • woaaaaaaahhhh... 非常感谢您.. 警告消失了.. 祝您有美好的一天,先生
猜你喜欢
  • 2018-01-31
  • 2018-03-27
  • 2019-01-05
  • 2019-06-17
  • 2018-09-14
  • 2020-01-06
  • 2021-11-04
  • 2020-04-18
  • 1970-01-01
相关资源
最近更新 更多