2017-01-09 13 views
0

我試圖實現終極版動作與使用陣營本地異步調用檢索一些JSON數據。我把函數fetchRestaurant()無處不在內部的元件,但我仍然得到這個錯誤:用減速異步調用不起作用

無法讀取屬性「類型的不確定

這裏的內部動作的代碼/ restaurant.js

export function setFetchedRestaurant(restaurants){ 
    return Object.assign({ type: types.SET_FETCHED_RESTAURANT, restaurants:restaurants }); 
} 



export function fetchRestaurant(){ 
    var restaurants; 
    fetch('https://appetizing.000webhostapp.com/connect.php').then((response) => response.text()).then((responseText) => { dispatch(setFetchedRestaurant(JSON.parse(responseText)));}).catch((error) => {console.warn(error);}); 

} 

,這是我到fetchRestaurant()函數我的組件內部呼叫:

componentDidMount(){ 
    this.props.fetchRestaurant(); 
} 

回答

2

您需要使用中間件來處理異步操作。一個這樣的中間件是Redux thunk。

這裏是你的行動的創建者寫成終極版咚:

export function fetchRestaurant() { 
    return (dispatch) => { 
     var restaurants 
     fetch('https://appetizing.000webhostapp.com/connect.php') 
      .then((response) => response.text()) 
      .then((responseText) => { 
       dispatch(setFetchedRestaurant(JSON.parse(responseText))); 
      }) 
      .catch((error) => { 
       console.warn(error); 
      }); 

    } 
} 

終極版 - 咚

記住這個工作你會插入配置時,終極版 - 咚到您的中間件鏈的Redux商店

import { createStore, applyMiddleware } from 'redux'; 
import thunk from 'redux-thunk'; 
import rootReducer from './reducers/index'; 

const store = createStore(
    rootReducer, 
    applyMiddleware(thunk) 
); 

Thunk Action創建者如何工作?

這個單一的thunk動作創建者是一個動作創建者,它將由我們的redux thunk中間件處理,因爲它適合與thunk動作創建者相關的簽名,即它返回一個函數。

當store.dispatch被調用時,我們的操作將在它們到達商店之前通過中間件鏈。 Redux Thunk是一箇中間件,它將會看到我們的動作是一個函數,然後賦予這個函數訪問商店的調度和獲取狀態。

這裏是終極版的thunk內的代碼,這是否:

if (typeof action === 'function') { 
    return action(dispatch, getState, extraArgument); 
} 

好了,所以這就是爲什麼我們的thunk行動的創建者返回的功能。因爲這個函數將被中間件調用並且讓我們訪問調度並且獲得狀態的含義,所以我們可以在稍後的日期發送進一步的行爲。

請記住,redux-thunk不是唯一的解決方案。如果我們想派發promise而不是函數,我們可以使用redux-promise。不過,我會建議從最簡單的解決方案開始使用redux-thunk。

終極版,承諾

的另一種方法來處理您的異步Redux的行動終極版thunk是終極版,承諾。您可以派遣返回承諾的操作創建者,而不是返回函數的操作創建者。

下面是一個例子:

function actionExample(payload){ 
    return new Promise((resolve, reject) => { 
     resolve(data); 
    }); 
} 

當然,你可以結合終極版,承諾和終極版,形實轉換的中間件,讓您可以調度函數調用調度時承諾解決了

+0

錯誤,但如果我用** console.log(response.text)打印響應; **與真實響應不同 – userfi

+0

好的,如果你的console.log(響應)怎麼辦?那應該給你整個迴應對象嗎? – therewillbecode

+0

我這樣做,答覆是空白的...... – userfi