反应-componentDidUpdate调用无限次

spl*_*unk 5 javascript reactjs

我是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 (
      <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);
Run Code Online (Sandbox Code Playgroud)

这就是我正在做的事情:在构造函数fetchMyWishlist中调用该操作,并返回书ID的数组。减速器currentCart使用fetchMyWishlist操作结果更新状态。

我不明白的第一件事是为什么在componentDidMount this.state.currentCart.payload中未定义。因此,我尝试componentDidUpdatethis.state.currentCart.payload定义的位置进行操作,并可以对其进行迭代。在这里,我为每本书尝试通过fetchSpecificBook操作检索其他信息。这里的问题是我收到无数次动作调用。我想做的是将所有其他书籍信息存储到一个数组中。

我该怎么办?

dsc*_*chu 0

为什么在 componentDidMount 中 this.state.currentCart.payload 未定义?

当您在构造函数内部时,您可以简单地设置状态,如下所示:

constructor(props) {
    super(props);
    this.state = {
        ...
    };
}
Run Code Online (Sandbox Code Playgroud)

当组件安装时,您的选择器应该为您提供所需的 props() 数据。您是否正在操纵商店并因此获得新的道具,从而导致无限的重新渲染循环?