简体   繁体   English

为什么我的 state 即使在编写 setState 方法后也没有更新?

[英]Why my state is not getting updated even after writing the setState method?

import React, { Component } from 'react'从“反应”导入反应,{组件}

class Columns extends Component{ constructor(props){ super(props) class 列扩展组件{构造函数(道具){超级(道具)

    this.state={
        message:'Hello'
    }
}

changeMessage(){
    
     this.setState=({
         message:'Welcome'
    })
}

render(){
    return(
        <div>
            <div>{this.state.message}</div>
            <button onClick={this.changeMessage}>Click</button>
        </div>
    )
}

} export default Columns } 导出默认列

As ray hatfield said above, you're losing the this context and need to use an arrow function, but also you're not calling setState ;正如上面的 ray hatfield 所说,你失去了this上下文,需要使用箭头 function,但你也没有调用setState you're overriding it.你正在覆盖它。

Remove the = from删除=

this.setState=({
     message:'Welcome'
})

so that it says:所以它说:

this.setState({
    message:'Welcome'
})

Because passing it as this.changeMessage detaches it from the component scope.因为将其作为this.changeMessage sage 传递会将其与组件 scope 分离。 When the button invokes it, "this" is no longer the component.当按钮调用它时,“this”不再是组件。

Change it to an arrow function: () => this.changeMessage()将其更改为箭头 function: () => this.changeMessage()

I've tried to explain this scope issue in another answer in the past if you want the details.如果您想了解详细信息,我过去曾尝试在另一个答案中解释此 scope 问题。

Also, as Aaron points out you also have an extraneous = in your changeMessage handler.此外,正如Aaron 指出的那样,您的 changeMessage 处理程序中还有一个无关的=

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM