我正在尝试使用redux将用户的当前位置设置为状态,但是每次尝试时,我都会不断收到错误消息Actions must be plain objects. Use custom middleware for async actions
。我到处看都说这是没有节制的错误,但是正如您从下面我的store.js中可以看到的那样applyMiddleware(thunk)
。这是我与此操作相关的所有文件:
store.js
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
const initialState = {};
const composeEnhancers = window._REDUX_DEVTOOLS_EXTENSION_COMPOSE_ || compose;
const store = createStore(
rootReducer,
initialState,
composeEnhancers(
applyMiddleware(thunk),
window.__REDUX_DEVTOOLS_EXTENSION__ ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f
)
);
export default store;
locationAction.js
export const setLocationState = () => {
dispatch => {
navigator.geolocation.getCurrentPosition((position) => {
dispatch({
type: SET_LOCATION,
payload: position
});
});
}
}
注意:即使我摆脱了派遣而只拥有该setLocationState()
功能,return type: SET_LOCATION
我也会遇到相同的错误,因此使我相信我可能在某处配置不正确。
locationReducer.js
const initialState = {
latitude: 0,
longitude: 0
}
export default (state = initialState, action) => {
switch(action.type) {
case SET_LOCATION:
return {
...state,
position: action.payload
}
default:
return state
}
}
index.jsx
import { setLocationState } from '../../../actions/locationActions'
const locationState = useSelector(state => state.location);
const dispatch = useDispatch();
dispatch(setLocationState()) // <- Here is where error occurs
setLocationState
看起来越野车:
export const setLocationState = () => {
dispatch => {
navigator.geolocation.getCurrentPosition((position) => {
dispatch({
type: SET_LOCATION,
payload: position
});
});
}
}
在这里,dispatch => {}
正在创建一个新的箭头函数,但不返回该箭头函数。因此,setLocationState
实际上将最终返回undefined
,这不是有效的操作对象。
简单的解决方法是return
在前面添加一个:return dispatch => {
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句