【问题标题】:React Redux with ESLint rules使用 ESLint 规则反应 Redux
【发布时间】:2019-02-03 15:55:21
【问题描述】:

在将 React 和 Redux 与 Airbnb 风格和 ESlint 规则一起使用时,我有一些困惑,主要是关于解构和上层范围:

import user from "./userModel";

class MyName extends Component {
  state = { user, size:0 };
render() {
    const {size}=this.state ; 
    const { username, items, location } = this.state.user;
    return (...)}}
MyName.propTypes = {createNewUser: PropTypes.func.isRequired
  // users: PropTypes.object};
const mapStateToProps = state => ({users: state.users});
export default connect(mapStateToProps,{ createNewUser})(MyName);

在解构状态的这段代码中,ESLint 说Must use destructuring state assignment (react/destructuring-assignment) 当我将其重写为

const {size, user}=this.state ; 
const { username, items, location } = user;

我又收到了

'user' is already declared in the upper scope. (no-shadow)

当我解构用户(商店)时显示相同类型的警告,例如const {users}=this.props;,它说'users' is missing in props validation (react/prop-types),当我在propTypes 中定义它时,它说object 被禁止

【问题讨论】:

  • 很难理解你对 player 做了什么,因为代码看起来不完整且不一致(有时你使用 state.player,其他时候使用 state.user,那么上限呢?)。我也许可以通过完整(一致的)代码示例为您提供帮助。关于 propTypes 如果PropTypes.object 被禁止,你可以尝试PropTypes.instanceOf(user) 代替,或者提供一个“看起来”像用户的形状:PropTypes.shape({ userName: PropTypes.string, items: ... })
  • @remix23 很抱歉这是一个错字,本地状态中有一个用户对象,商店中有用户。在复制粘贴中有错误。我编辑了问题

标签: reactjs react-redux eslint redux-thunk


【解决方案1】:

您可以在解构时“重命名”变量以防止冲突:

const { size, user: currentUser } = this.state;

this.state.user 获取值并将其分配给currentUser

【讨论】:

  • 谢谢,警告消失了。但是我在官方文档中没有看到这样的提示。
  • “react/destructuring-assignment”规则是否有显着优势?随着强制重命名,它会导致更多,而不是更少的问题。
  • 这主要是意见/背景问题。如果您必须重命名所有内容,那么可能不值得。如果您只需要重命名一个数字中的 1 个,那可能没问题。
猜你喜欢
  • 2019-02-04
  • 1970-01-01
  • 2021-10-16
  • 2017-06-21
  • 2020-10-21
  • 2020-08-04
  • 2020-01-19
  • 2016-04-14
  • 1970-01-01
相关资源
最近更新 更多