2017-04-19 91 views
2

我正在處理反應,並且我有這3個文件(組件,動作和縮減器)。在這裏,他們是:道具是未定義的,但狀態已定義

cart.js看起來是這樣的:

import React, {Component} from 'react'; 
import { connect } from 'react-redux'; 
import { fetchMyWishlist } from '../actions/index'; 
class Cart extends Component { 

    constructor(props) { 
    super(props); 
    } 

    componentWillMount(){ 
     this.props.fetchMyWishlist(this.props.signedInUserInfo._id); 
    } 
    } 

    renderWishList(){ 
      console.log("ANOTHER TEST:"+ JSON.stringify(this.props.currentCart)); 
    } 

    render(){ 
    return ({this.renderWishlist()}); 
    } 
} 



    function mapStateToProps(state){ 
    console.log("TEST: "+state.bookReducer.currentCart); 
    return { 
     currentCart: state.bookReducer.currentCart 
    }; 
    } 

    export default connect(mapStateToProps, {fetchMyWishlist})(Cart); 

行動是這裏面的動作/ index.js:

export function fetchMyWishlist(userId){ 
    let url = 'http://localhost:3001/cart/'+userId; 
    return function (dispatch) { 
    axios.get(url) 
     .then(response => { 
     dispatch({ 
      type: FETCH_WISHLIST, 
      payload: response.data 
     }); 
     }); 
    } 
} 

這裏是我的減速

import {FETCH_BOOKS} from '../actions/types'; 
import {FETCH_WISHLIST} from '../actions/types'; 
const INITIAL_STATE = { myBooks:[], currentCart:[] }; 

export default function(state = INITIAL_STATE, action) { 
    switch (action.type) { 
    case FETCH_BOOKS: 
     return { ...state, myBooks:action.payload }; 
    case FETCH_WISHLIST: 
     return { ...state, currentCart: action.payload }; 
    default: 
     return state; 
    } 
} 

我的問題是,我不明白爲什麼我從2只console.log買這個2分的結果:

TEST: [object Object] 
ANOTHER TEST: undefined 

正如你所看到的減速做它的工作,但我不明白爲什麼this.props。 currentCart是未定義的。

+0

不應'mapStateToProps'和'出口default'聲明的函數定義是_after_你'Cart'類聲明的右大括號? –

回答

0

我認爲你錯誤地將參數傳遞給JSON.stringify。你不應該使用這樣的

console.log("ANOTHER TEST: " + JSON.stringify(this.props.currentCart)); 
0

試着改變你的方法渲染:

renderWishList(){ 
      console.log(this.props.currentCart); 
    } 

看來你要使用JSON.stringify一個參數不是通過附加「另一個JSON測試:因爲它的背景將是窗」,它不會工作

//very wrong 
JSON.stringify("ANOTHER TEST: "+this.props.currentCart)); 
+0

是的,你是對的,我寫了代碼在這裏,但我的電腦中的代碼沒有這個錯字 – splunk

+0

,所以如果你的代碼沒有這個問題,然後嘗試控制檯日誌中的所有道具'renderWishList()'讓看看發生什麼事 – cabolanoz

0

this.props.currentCart是不確定的。

如果您在渲染方法中記錄道具的內容,您應該會看到期望的值。

this :)上結合上下文正確條

相關問題