1
每次我試圖派遣我的動作時間,我得到這個錯誤:錯誤:操作必須是普通對象。使用自定義中間件進行異步操作。在反應本土
Error: Actions must be plain objects. Use custom middleware for async actions.
我已經安裝redux-thunk
和無異步行爲,它的工作。
存儲配置:
import { applyMiddleware, createStore } from 'redux';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
import { composeWithDevTools } from 'redux-devtools-extension';
import reducers from '../reducers/index';
const logger = createLogger();
export default createStore(reducers, composeWithDevTools(applyMiddleware(thunk)));
UI:
...
import { connect } from 'react-redux';
import { getCities } from '../../actions/cities';
...
componentDidMount = async() => {
try {
const cities = await this.props.getCities();
console.log(cities);
} catch (error) {
console.log(`errorhome: ${error}`);
}
SplashScreen.hide();
}
...
const mapDispatchToProps = dispatch => ({
changeNetworkStatus:() => dispatch(changeNetworkStatus),
getCities:() => dispatch(getCities),
});
export default connect(mapStateToProps, mapDispatchToProps)(Home);
操作:
import database from '../config/utils';
export const GET_CITIES_START = 'GET_CITIES_START';
export const GET_CITIES_FINISHED = 'GET_CITIES_FINISHED';
export const GET_CITIES_ERROR = 'GET_CITIES_ERROR';
const getCititesStart =() => ({ type: GET_CITIES_START });
const getCititesFinished = cities => ({ type: GET_CITIES_FINISHED, cities });
const getCititesError = error => ({ type: GET_CITIES_ERROR, error });
export const getCitites =() => async (dispatch) => {
dispatch(getCititesStart());
try {
const cities = [];
const snap = await database.ref('cities').once('value');
console.log('snap: ', snap);
snap.forEach((element) => {
const city = {
city: element.key,
coordinate: element.val().coordinate,
};
cities.push(city);
});
dispatch(getCititesFinished(cities));
} catch (error) {
dispatch(getCititesError(error));
}
};
編輯:如果我添加logger
到中間件過,該錯誤信息是這樣的:
TypeError: Cannot read property 'type' of undefined
感謝您的幫助!
哦....尼斯... :)謝謝!它幫助!但我得到了一個不同的消息:'TypeError:(0,_cities.getCities)不是一個函數':(它看起來像我試圖稱它爲'this.props.getCities()'時它的工作原理是這樣的: '函數getCities(){dispatch((0,_cities.getCities)());}' –
沒關係,那是一個錯字.....再次感謝! –