2017-01-21 39 views
0

我正在使用Redux從API加載數據& React。儘管成功地將這些數據提取並應用到了狀態,但它卻引發了一個錯誤。Redux無法讀取未定義的屬性'payload'

「Uncaught TypeError:無法讀取未定義的屬性」有效載荷「。這發生在控制檯中的FETCH_PRODUCT_LISTINGS_PENDING操作類型之後。

陣營組件:

import React from 'react'; 
import { connect } from 'react-redux'; 
import store from '../../../store'; 

import * as ProductListingActions from '../actions/ProductListingActions'; 

@connect((store) => { 
    return { 
     productListing: store.productListing.products 
    } 
}) 

export default class ProductListingContainer extends React.Component { 
    constructor(data) { 
     super(); 
     this.props = data; 
     this.props.dispatch(ProductListingActions.fetchProductListings()); 
    } 
    render() { 
     return <div></div>; 
    } 
} 

減速機:

import CookieHandler from '../../../modules/CookieHandler'; 
const cookieHandler = new CookieHandler; 

export default function reducer(
    state = { 
     products: [], 
     fetching: false, 
     fetched: false, 
     error: null 
    }, action) { 

    switch(action.type) { 
     case "FETCH_PRODUCT_LISTINGS_PENDING": 
      return { 
       ...state, 
       fetching: true, 
      } 
      break; 
     case "FETCH_PRODUCT_LISTINGS_REJECTED": 
      return { 
       ...state, 
       fetching: false, 
       error: action.payload 
      } 
      break; 
     case "FETCH_PRODUCT_LISTINGS_FULFILLED": 
      return { 
       ...state, 
       fetching: false, 
       fetched: true, 
       products: action.payload.data.default 
      } 
      break; 
    } 

    return state; 
} 

操作:

import Config from '../../../Config.js'; 
import store from '../../../store.js'; 
import axios from 'axios'; 

export function fetchProductListings() { 
    store.dispatch({ 
     type: "FETCH_PRODUCT_LISTINGS", 
     payload: axios.get(Config.getConfigAPIUrl() + '/cartel/products') 
    }) 

} 

任何幫助將是appre ciated

回答

1

您正在調度調度而不是調度對象。

如果內聯這樣的:

this.props.dispatch(
    store.dispatch({ 
    type: "FETCH_PRODUCT_LISTINGS", 
    payload: axios.get(Config.getConfigAPIUrl() + '/cartel/products') 
    }) 
) 

你行動的創建者不應該叫調度,它應該只是返回一個動作:

export function fetchProductListings() { 
    return { 
    type: "FETCH_PRODUCT_LISTINGS", 
    payload: axios.get(Config.getConfigAPIUrl() + '/cartel/products') 
    } 
} 

但請記住,axios.get是異步,所以​​將承諾。您可能需要考慮添加redux-thunk來處理兌現承諾。

+0

完美,工作的魅力!謝謝 – DorianHuxley

+0

注 - 我已經在使用redux-thunk了,但是感謝提示:) – DorianHuxley

0

除非您提供更多信息,唯一會導致信息未被定義的信息是action.payload。也許這是action.payLoad?仔細檢查API返回的內容,確保它確實是action.payload

相關問題