道具是未定义的,但状态已定义
问题描述:
我正在处理反应,并且我有这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是未定义的。
答
我认为你错误地将参数传递给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));
不应'mapStateToProps'和'出口default'声明的函数定义是_after_你'Cart'类声明的右大括号? –