使用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();
}
如果我将原型改写为
,则会破坏玩家的身体GameInit.propTypes = {
createNewPlayer: PropTypes.func.isRequired,
players: PropTypes.object.isRequired, // Prop type `object` is forbidden (react/forbid-prop-types)
};
在这里遵循ESLint规则的正确方法是什么?而不更改.eslintrc
答案 0 :(得分:2)
这可能会解决您的第一个问题:
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
}),