首页 > 解决方案 > Thunk + Redux(在 React Native 中):无法让操作生效

问题描述

我是这个堆栈的新手。我已经看到了很多关于此的其他问题,并阅读了 Thunk 文档,但我无法将它们拼接在一起。

当我运行下面的代码时,我收到错误“操作必须是普通对象,使用自定义中间件进行异步操作”,这正是我试图用 Thunk 解决的问题。

我的动作是这样的:

src/actions/recipes.js

// this calls the API
function fetchApiGetRecipes() {
  return fetch('https://mywebsite.com/endpoint/', {
    method: 'GET',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + idToken
    }
  }).then((json) => {
    dispatch({
      type: 'RECIPES_REPLACE',
      data: json
    })

  });
}

// this is passed into my container to use to refresh the recipe list
export function getRecipes() {    
  if (Firebase === null) return () => new Promise(resolve => resolve());

  if (Firebase.auth().currentUser !== null) {
          Firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {            
            // console.log(idToken);
            return dispatch => new Promise(resolve => fetchApiGetRecipes(idToken) )                  
          }).catch(function(error) {
            // Handle error
          });

  } else {
    console.log("Null user");
  }

}

在此处使用 Thunk 并修复应用程序启动时出现的错误的正确语法是什么?

编辑:我创建这样的商店:

import { createStore, applyMiddleware, compose } from 'redux';
import { persistStore, persistCombineReducers } from 'redux-persist';
import storage from 'redux-persist/es/storage'; // default: localStorage if web, AsyncStorage if react-native
import thunk from 'redux-thunk';
import reducers from '../reducers';

// Redux Persist config
const config = {
  key: 'root',
  storage,
  blacklist: ['status'],
};

const reducer = persistCombineReducers(config, reducers);

const middleware = [thunk];

const configureStore = () => {
  const store = createStore(
    reducer,
    window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
    compose(applyMiddleware(...middleware)),
  );

  const persistor = persistStore(
    store,
    null,
    () => { store.getState(); },
  );

  return { persistor, store };
};

export default configureStore;

标签: redux-thunk

解决方案


您的getRecipes函数不会在if (Firebase.auth().currentUser !== null)子句中返回函数。

你需要返回一个你正在做的函数

Firebase.auth().currentUser.getIdToken(/* forceRefresh */ true).then(function(idToken) {            
            // console.log(idToken);
            return dispatch => new Promise(resolve => fetchApiGetRecipes(idToken) )                  
          }).catch(function(error) {
            // Handle error
          });

dispatch 函数(我假设是要返回的函数)then在 promise 的子句中返回。这不会将调度函数返回到外部方法getRecipies。因此错误


推荐阅读