作者:kyle_G_476 | 来源:互联网 | 2023-02-06 04:49
我是React的新手,我觉得我没有抓住组件生命周期流程,这是我拥有的组件:
import React, {Component, PropTypes} from 'react';
import { connect } from 'react-redux';
import { fetchMyWishlist, fetchSpecificBook } from '../actions/index';
class Cart extends Component {
static cOntextTypes= {
router:PropTypes.object
};
constructor(props) {
super(props);
this.state = { currentCart:[], currentBook:[], wishlist:[] };
var self = this;
if (this.props.authenticated){
this.props.fetchMyWishlist(this.props.signedInUserInfo._id).then(function(data){
self.setState({ currentCart: data});
});
}
else {
this.context.router.push('/signin');
}
}
componentWillMount(){}
componentDidMount(){
// I get undefined here
console.log("component has been mounted: "+this.state.currentCart.payload);
}
componentDidUpdate(prevProps, prevState){
var jsOnObj= this.state.currentCart.payload;
console.log("test: "+JSON.stringify(this.state.currentCart.payload));
var self = this;
if ((jsonObj) && (jsonObj.data)){
return jsonObj.data.map(function(book){
self.props.fetchSpecificBook(book.itemID);
});
}
}
render() {
console.log("rendering");
return (
);
}
}
function mapStateToProps(state){
return {
currentCart: state.bookReducer.currentCart,
currentBook: state.bookReducer.currentBook,
authenticated: state.auth.authenticated,
signedInUserInfo:state.auth.signedInUserInfo
};
}
export default connect(mapStateToProps, {fetchMyWishlist, fetchSpecificBook})(Cart);
这就是我正在做的事情:在构造函数fetchMyWishlist
中调用该操作,并返回书ID的数组。减速器currentCart
使用fetchMyWishlist
操作结果更新状态。
我不明白的第一件事是为什么在componentDidMount this.state.currentCart.payload
中未定义。因此,我尝试componentDidUpdate
在this.state.currentCart.payload
定义的位置进行操作,并可以对其进行迭代。在这里,我为每本书尝试通过fetchSpecificBook
操作检索其他信息。这里的问题是我收到无数次动作调用。我想做的是将所有其他书籍信息存储到一个数组中。
我该怎么办?