【问题标题】:Do not mutate state directly. Use setState() react/no-direct-mutation-state不要直接改变状态。使用 setState() 反应/无直接突变状态
【发布时间】:2017-11-19 08:28:34
【问题描述】:

我有这个代码:

constructor(props) {
    super(props)
    this.state = {
        loginButton: '',
        benchmarkList: ''
    }
    if (props.username == null) {
        this.state.loginButton = <GoogleButton></GoogleButton>
    } else {

    }
}

它给了我一个 ESLint 警告:

不要直接改变状态。使用 setState() 反应/无直接突变状态。

现在我该怎么办,因为我不能在 constructor 中直接使用 setState,因为它会创建 error,并且像这样更新会出错。

【问题讨论】:

  • 设置this.state 不必是第一个语句;你可以先设置各种vars,然后用它们组成this.state
  • 只是把这个扔在这里,在状态中存储一个 React 组件可能不是最好的方向
  • 确实,更好的解决方案是在渲染对象中使用{ !this.state.username &amp;&amp; &lt;GoogleButton /&gt; }
  • @rossipedia 为什么会这样,它会减慢渲染或状态变化检测吗?
  • 虽然没有什么技术上阻止您这样做,但它违反了将所有 UI 逻辑都放在 render() 方法中的惯例。我想不起来了,但我还记得读过一些其他的陷阱。

标签: javascript reactjs


【解决方案1】:

首先,我们不应该将ui组件存储在状态变量中,状态应该只包含数据。所有的 ui 部分都应该在 render 方法中。

如果您想根据任何数据render 某个组件,请使用conditional rendering。检查this.state.loginButton 的值,如果是null,则渲染该按钮。

像这样:

constructor(props) {
    super(props)
    this.state = {
        loginButton: props.username,
        benchmarkList: ''
    }
}

render(){
    return(
        <div>
            {!this.state.loginButton ? <GoogleButton></GoogleButton> : null}
        </div>
    )
}

理想情况下,我们也不应该将props 的值存储在state 中,所以直接使用this.props.username,我这样做是因为不知道完整的代码。

【讨论】:

  • 好的。我明白你在视图中使用条件的观点。但是,当该属性仅由父级控制时,为什么我要将 props 属性存储到 state 属性中?
  • @JennaWesley 伙计,我只是展示了更好的方法,不知道您的完整代码。您也不应该将 props 存储在 state 中,直接由 this.props.username 使用。
  • 我想可能是你在这个组件的某个地方更新了这个值,这就是原因。
  • 谢谢。我学到了很多,并且已经实现了这个答案的技术
【解决方案2】:
constructor(props) {
    super(props)
    this.state = {
      loginButton: props.username == null? <GoogleButton></GoogleButton>: '',
      benchmarkList: ''
    }
  }

或者你可以在componentWillMount()中使用setState

componentWillMount(){
   let loginButton = props.username == null? <GoogleButton></GoogleButton>: '';
   this.setState({loginButton: loginButton});
}

【讨论】:

  • 第一种方法最终会使代码变得混乱,但我可以做类似的事情。先准备好变量再this.state = ...
  • 问题是关于constructor 但是componentWillMount 是个好地方。
【解决方案3】:

如何在 ReactJS 中更新 constructor 内部的状态?

创建数据结构,根据需要进行修改,并在所有完成后分配给状态:

constructor(props) {
    super(props)
    let state = {
        loginButton: '',
        benchmarkList: ''
    }
    if (props.username == null) {
        state.loginButton = true
    } else {
        state.loginButton = false
    }
    this.state = state
}

【讨论】:

    【解决方案4】:

    只需添加 setState

    if (props.username == null) {
    
           this.setState({
                loginButton: <GoogleButton></GoogleButton>
           })
    
    } else {
    
    
    

    【讨论】:

      猜你喜欢
      • 2021-11-28
      • 2019-07-10
      • 1970-01-01
      • 2021-09-11
      • 2018-04-24
      • 2017-09-27
      • 2019-12-22
      • 2019-10-02
      • 2020-10-23
      相关资源
      最近更新 更多