【问题标题】:Reactjs ; destructuring props assignment with ESLint rules反应js;使用 ESLint 规则解构 props 分配
【发布时间】:2019-02-04 21:25:28
【问题描述】:

使用 ESLing 插件进行反应我在解构和道具类型验证方面感到困惑。 在下面的课堂上

class Game extends Component {

  componentWillMount() {
    this.props.createNewPlayer(); //  Must use destructuring props assignment (react/destructuring-assignment)
  }

  render() {
    const { players } = this.props; // 'players' is missing in props validation (react/prop-types)
    const count = Object.keys(players).length;
    return (...);
  }
}

GameInit.propTypes = {createNewPlayer: PropTypes.func.isRequired};

const mapStateToProps = state => ({players: state.players});

export default connect(mapStateToProps,{ createNewPlayer })(Game);

所以如果我将第一部分的结构重写为

  componentWillMount() {
    const {createNewPlayer}=this.props; // 'createNewPlayer' is already declared in the upper scope. (no-shadow) 
    createNewPlayer();
  }

如果我将proptypes重写为播放器的解构

GameInit.propTypes = {
  createNewPlayer: PropTypes.func.isRequired,
  players: PropTypes.object.isRequired, // Prop type `object` is forbidden (react/forbid-prop-types)
};

这里遵循 ESLint 规则的正确方法是什么?不改变.eslintrc中的规则

【问题讨论】:

  • 同时禁用复杂对象的行作品。 // eslint-disable-line [规则名称]

标签: reactjs react-redux eslint eslint-config-airbnb


【解决方案1】:

这可能会解决您的第一个问题:

const {createNewPlayer: createNewPlayerAlt } = this.props;
createNewPlayerAlt();

对于第二部分,您应该在此处指定您拥有的对象类型。

所有属性都是字符串的对象:

players: PropTypes.objectOf(PropTypes.String)

所有属性都是数字的对象:

players: PropTypes.objectOf(PropTypes.Number)

你有混合属性吗?那就去shape:

player: PropTypes.shape({
    id: PropTypes.string,
    playerNumber: PropTypes.number
  }),

【讨论】:

  • 谢谢,哈哈,我的播放器模型很复杂,规则上还是忽略吧。
  • 当您的数据有问题时,道具类型是好的。但是对于复杂的对象,是的,在某个地方会很痛苦 :) 一两个不是问题,但是当您的应用程序变得更大时,很难耐心地编写所有这些对象。
猜你喜欢
  • 2019-02-03
  • 1970-01-01
  • 1970-01-01
  • 2023-04-03
  • 2022-01-13
  • 1970-01-01
  • 1970-01-01
  • 2021-12-26
  • 2020-03-25
相关资源
最近更新 更多