android - Redux-Thunk:动作必须是普通对象。使用自定义中间件进行异步操作
问题描述
无法解决这个问题,使用 react-native 和 redux-thunk。
我正在尝试将数据发布到 firebase.io 并反复收到相同的错误:操作必须是普通对象。使用自定义中间件进行异步操作。
减速器/index.js
import { createStore, combineReducers, compose, applyMiddleware } from 'redux';
import thunk from 'redux-thunk'
import PlacesReducer from './placesReducer'
const rootReducer = combineReducers({
places : PlacesReducer,
});
let composeEnhancers = compose;
if (__DEV__) {
composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
}
const configureStore = () => {
return createStore(rootReducer, applyMiddleware(thunk));
};
export default configureStore;
动作/index.js
export const addPlace = (placeName, location, image) => {
return dispatch => {
const placeData = {
name: placeName,
location: location
};
fetch("https://awesome-places-b592c.firebaseio.com/placesReducer.json", {
method: "POST",
body: JSON.stringify(placeData)
})
.catch(err => console.log(err))
.then(res => res.json())
.then(parsedRes => {
console.log(parsedRes);
});
};
};
减速器/placesReducer.js
const initialState = {
places: []
};
const reducer = (state = initialState, action) => {
switch (action.type) {
case "ADD_PLACE":
return {
...state,
places: state.places.concat({
key: Math.random(),
name: action.placeName,
image: {
uri: action.image.uri,
location: action.location
}
})
};
default:
return state;
}
};
export default reducer;
感谢所有帮助,谢谢。
更新
createStore()
在 reducers/index.js中为函数添加了 initialState 参数
const configureStore = () => {
return createStore(rootReducer, {places: []}, applyMiddleware(thunk));
};
仍然收到相同的错误
解决方案
您需要dispatch
在异步请求完成后执行这些操作
.then(parsedRes => {
console.log(parsedRes);
dispatch({
type: YOUR_REDUCER_TYPE,
parsedRes
})
});
同样如createStore
文档中所述,您需要添加initialState
(reducer, preloadedState, enhancer)
推荐阅读
- java - 如何解决“找不到符号”的问题?
- c# - C# System.Text.Json JSON 值无法转换为类结构
- mysql - 我在 docker 上设置了 mysql 和 apache 超集并通过桥接网络连接,SQLAlchemy URI 是什么?
- firebase - 退出后无法登录 - Firebase Google Signin with Flutter
- django - DJANGO - 模型中的默认过滤器
- reactjs - Material UI:访问子节点
- 零件
- javascript - 在项目中包含 X 射线刮刀时出现 Npm 错误
- reactjs - React Typesscript 消费组件回调
- android - 无法关闭或点击 Admob 应用
- r - 手动创建的公式似乎不起作用……但为什么呢?