2017-08-09 21 views
0

我試圖將Redux添加到我的測試應用程序,但我無法從API獲取數據。感覺就像我已經完成了所有的步驟,但是我無法從我的組件中獲取道具,所以我在這個道路上一直在搞亂。我的代碼:Redux獲取不通過

動作/ index.js:

import 'whatwg-fetch'; 
import ReduxThunk from 'redux-thunk'; 

export const FETCH_RECIPES = 'FETCH_RECIPES'; 
const ROOT_URL = 'http://myapi/recipe/'; 

export function fetchRecipes(id) { 
    const url = ROOT_URL + "0"; 
    // const request = fetch(url); 
    return (dispatch) => { 
    fetch(url) 
     .then((response) => response.json()) 
     .then((request) => dispatch(fetchRecipesSuccess(request))) 
    }; 
} 

export function fetchRecipesSuccess(request) { 
    return { 
     type: FETCH_RECIPES, 
     request 
    }; 
} 

reducer_recipe.js:

import { FETCH_RECIPES } from "../actions/index"; 

export default function(state = [], action) { 
    switch(action.type) { 
     case FETCH_RECIPES: 
      return [action.payload.data, ...state]; 
    } 

    return state; 
} 

減速/ index.js:

import { combineReducers } from 'redux'; 
import RecipesReducer from './reducer_recipes'; 

const rootReducer = combineReducers({ 
    recipes: RecipesReducer 
}) 

export default rootReducer; 

aaaaand在我的部分我m使用該代碼:

function mapStateToProps({ recipes }) { 
    return { recipes }; 
} 

connect(mapStateToProps, {fetchRecipes})(Recipe); 

在我index.js我創建我的商店與const createStoreWithMiddleware = createStore(reducers, applyMiddleware(ReduxPromise));

隨着我想我應該是很好的使用this.props訪問我已經獲取從我的API數據,但我想我將數據放在某處。我錯過了什麼?

+0

是的,檢查你的減速機。你應該返回'action.request.data'。你可以通過console.log操作對象來看看你有什麼 – Rowland

回答

1

檢查你的減速機。您似乎正在返回action.payload.data,而在您的fetchRecipesSuccess中,它的名稱爲request。你可以console.log行動對象,看看你有什麼

import { FETCH_RECIPES } from "../actions/index"; 

export default function(state = [], action) { 
    switch(action.type) { 
    case FETCH_RECIPES: 
     // Verify here that your request object has data 
     return [...state, action.request.data]; 
     // Default state 
    default: 
     return state; 
    } 
} 

希望這有助於!

+0

感謝您的快速回答!這是我的一個大錯過。雖然,當我console.log(action.request.data)沒有任何反應 - 這就好像減速機沒有運行在我的應用程序。我必須以某種方式連線嗎? – hejhej123

+0

您是否可以驗證您是否將reducer作爲'redurs'導入它的方式=>'const createStoreWithMiddleware = createStore(reducer,applyMiddleware(ReduxPromise));' – Rowland

+0

是的,這就是我的代碼的外觀,我正在包裝我的用''。 – hejhej123