redux-thunk - 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;
解决方案
您的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
。因此错误
推荐阅读
- .htaccess - htaccess 使用 SSL 和文件扩展名重写非 www
- javascript - 为什么延迟修改 DOM?
- java - Javafx gif 内存泄漏
- php - 在 Woocommerce 购物车小部件中显示购物车项目数
- xcode - xCode:目前无法安装此应用程序。仅在添加 watchOS 扩展后出现此错误
- php - 在 Codeigniter 中进行插入时出现内部服务器错误
- layout - Flutter 如何在 ListTile 中使用文本字段?
- graphql-js - graphql-compose-mongoose 生成错误:预期 [object Object] 是 GraphQL 模式
- python-3.x - 如何使用 python3 从文本中拆分复合名词,例如物联网?
- c - 创建更通用的 makefile