2017-10-15 60 views
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

感謝您的幫助!

回答

1

動作是返回一個包含動作數據的對象的函數,該數據是一個具有type屬性的對象。

你調度動作是這樣的:

dispatch(getCities) 

你應該派遣行動是這樣的:

dispatch(getCities()) 
+0

哦....尼斯... :)謝謝!它幫助!但我得到了一個不同的消息:'TypeError:(0,_cities.getCities)不是一個函數':(它看起來像我試圖稱它爲'this.props.getCities()'時它的工作原理是這樣的: '函數getCities(){dispatch((0,_cities.getCities)());}' –

+0

沒關係,那是一個錯字.....再次感謝! –

相關問題