我是新來的反應,我覺得我沒趕上組件的生命週期流程,這是我有分量:陣營 - componentDidUpdate稱爲無限次
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 (
<div>
<div>
<h3>Your wishlist</h3>
</div>
</div>
);
}
}
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
,它返回一個book ID數組。減速器更新currentCart
狀態,結果爲fetchMyWishlist
動作。
我不明白的第一件事是爲什麼componentDidMount this.state.currentCart.payload
未定義。 因此,我嘗試在componentDidUpdate
內執行我的操作,其中this.state.currentCart.payload
已定義,我可以遍歷它。 這裏對於每本書,我嘗試通過fetchSpecificBook
操作檢索附加信息。 這裏的問題是,我得到無限次數的動作調用。 我想要做的是將所有其他書籍信息存儲到數組中。
我該如何解決這個問題?
我會建議到生命週期的方法,並有流:https://facebook.github.io/react/docs/react-component.html#the-component-lifecycle,你會得到錯誤的原因。 –
我已經刪除了'redux'標籤,因爲您使用的是redux庫而不是redux體系結構。 – Sulthan