无法在componentDidMount中调用props函数

时间:2018-08-16 14:25:51

标签: reactjs react-redux eslint

从将Party与mapStateToProps和mapDispatchToProps连接的Party.Container中,向Party发送两个函数(fetchData和fetchFooter)

他们一直工作到我在项目eslint:“ airbnb”中实现之前,现在不断出现此错误“必须使用破坏性道具分配反应/破坏性分配”。

const mapActionsToProps = {
fetchData,
fetchDataFooter,};

---这些是功能

componentDidMount() {
  this.props.fetchData();
  this.props.fetchDataFooter(); }

这是组件

import { connect } from 'react-redux';
import { fetchData, fetchDataFooter } from './actions';

import Party from './Party';

const mapStateToProps = state => ({
  wishlist: state.wishlist,
  cart: state.cart,
});

const mapActionsToProps = {
  fetchData,
  fetchDataFooter,
};

export default connect(mapStateToProps, mapActionsToProps)(Party);
This is COntainer

import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Header from '../../components/Header/Header';
import Content from './Content/Content.Container';
import styles from './Party.module.scss';
import Footer from '../../components/Footer/Footer';

const propTypes = {
  wishlist: PropTypes.shape.isRequired,
  cart: PropTypes.shape.isRequired,
  // fetchData: PropTypes.func.isRequired,
  // fetchDataFooter: PropTypes.func.isRequired,
};

class Party extends Component {
  componentDidMount() {
    // this.props.fetchData();
    // this.props.fetchDataFooter();
  }

  render() {
    const { wishlist, cart } = this.props;
    let name;
    let profilePicture;
    let personWishlist;
    let purchases;
    let id;
    if (wishlist.isFulfilled === true) {
      const listId = wishlist.payloadData.data.filter(x => x.id === 1);
      ({ name } = listId[0].name);
      ({ profilePicture } = listId[0].picture);
      ({ personWishlist } = listId[0].wishList);
      ({ purchases } = listId[0].purchases);
      ({ id } = listId[0].id);
    }
    console.log(wishlist, cart);
    return (
      <div className={styles.Party}>
        <Header />
        <Content
          name={name}
          id={id}
          profilePicture={profilePicture}
          personWishlist={personWishlist}
          purchases={purchases}
        />
        <Footer
          cart={cart}
        />
      </div>
    );
  }
}

Party.propTypes = propTypes;

export default Party;

2 个答案:

答案 0 :(得分:1)

由于错误提示,您可以在componentDidMount方法中尝试以下方法吗?

componentDidMount() {
   const { fetchData, fetchDataFooter } = this.props;
   fetchData();
   fetchDataFooter();
}

答案 1 :(得分:1)

实际上,这意味着您的表达式在使用前应先进行重构。

例如:您正在使用:

...
this.props.fetchData();
this.props.fetchDataFooter();
...

您必须将其更改为:

const { fetchData, fetchDataFooter } = this.props;
fetchData();
fetchDataFooter();

另一种解决方案是,如果要在规则文件中禁用此功能。

"react/destructuring-assignment": [<enabled>, 'always']-可以是alwaysnever

有关更多信息,请参见here