道具是未定义的,但状态已定义

道具是未定义的,但状态已定义

问题描述:

我正在处理反应,并且我有这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'类声明的右大括号? –

我认为你错误地将参数传递给JSON.stringify。你不应该使用这样的

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

试着改变你的方法渲染:

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

看来你要使用JSON.stringify一个参数不是通过附加“另一个JSON测试:因为它的背景将是窗”,它不会工作

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

是的,你是对的,我写了代码在这里,但我的电脑中的代码没有这个错字 – splunk

+0

,所以如果你的代码没有这个问题,然后尝试控制台日志中的所有道具'renderWishList()'让看看发生什么事 – cabolanoz

this.props.currentCart是不确定的。

如果您在渲染方法中记录道具的内容,您应该会看到期望的值。

this :)上结合上下文正确条