虽然this.state是一个Javascript对象,但为什么即使向其中传递了一个包含数据的状态,state仍然为null?

虽然this.state是一个Javascript对象,但为什么即使向其中传递了一个包含数据的状态,state仍然为null?,javascript,reactjs,Javascript,Reactjs,我有以下代码(见下文) 我希望它显示用户名,它是firstName和lastName的组合。为什么下面的代码不起作用 我希望它能展示出来 欢迎Daggie Blanqx 类头扩展React.Component{ 建造师(道具){ 超级(道具); 此.state={ 名字:“Daggie”, 姓氏:“Blanqx”, 用户名:()=>(this.state.firstName+this.state.lastName) } } render(){ 返回( 欢迎{this.state.userName

我有以下代码(见下文)

我希望它显示用户名,它是firstName和lastName的组合。为什么下面的代码不起作用

我希望它能展示出来

欢迎Daggie Blanqx

类头扩展React.Component{
建造师(道具){
超级(道具);
此.state={
名字:“Daggie”,
姓氏:“Blanqx”,
用户名:()=>(this.state.firstName+this.state.lastName)
}
}
render(){
返回(
欢迎{this.state.userName}

) } }
在您的示例中,您正在访问函数
this.state.userName
您需要像这样调用该函数
this.state.userName()

this.state.userName
将返回您需要在函数末尾放置的
()
变量获取
返回
函数值
你知道为什么它不起作用了

尽量避免在state对象中使用方法,因为您似乎在向状态中插入函数,因此需要调用它以获得结果。一般来说,不建议将这样的函数置于状态。但是,如果您仍然希望使用该方法,请尝试以下方法:

<p>Welcome , {this.state.userName()} !</p>
然后在模板中:

<p>Welcome , {this.getUserName()} !</p>
欢迎,{this.getUserName()}

您缺少()

欢迎{this.state.userName()}

也不需要为此定义函数,直接得到这样的结果

<p>Welcome , {this.state.firstName} {this.state.lastName} !</p>
欢迎,{this.state.firstName}{this.state.lastName}


它应该抛出一个错误,因为您正试图与状态交互,但状态尚未初始化。为此,请使用
componentDidMount()
+
prevState
或将其放入
render()

变体1

import React,{Component}来自“React”
导出默认类头扩展组件{
建造师(道具){
超级(道具)
此.state={
名字:“Daggie”,
姓氏:“Blanqx”
}
}
render(){
返回(
欢迎{this.state.firstName+this.state.lastName}

) } }
变体2

import React,{Component}来自“React”
导出默认类头扩展组件{
建造师(道具){
超级(道具)
此.state={
名字:“Daggie”,
姓氏:“Blanqx”,
全名:“”
}
}
componentDidMount(){
this.setState(prevState=>({
全名:prevState.firstName+prevState.lastName
}))
}
render(){
返回(
欢迎{this.state.fullName}

) } }
您的意思是
{this.state.userName()}
?您在自己的状态下定义函数有什么原因吗?当前正在返回函数,您需要添加括号,例如{this.state.userName()}来调用函数为什么说“尽量避免在状态对象中使用方法”…有没有更好的方法从名字和姓氏中调用用户名?是的,这是因为它可以,但您有复杂的函数。它不好。当我们在EventHandler中调用函数时,我们不使用()…为什么这种情况是例外?react和vanilla JavaScript之间有区别。例如,在react中,您将传递对函数的引用。例如:当有人实际执行单击时,组件“div”将触发传递到onClick处理程序的函数。与vanilla javascript相比,在vanilla javascript中,当有人单击div时,您会传递字符串。您可以在此处阅读更多有关内容:
<p>Welcome , {this.getUserName()} !</p>
<p> Welcome {this.state.userName()} !</p>
<p>Welcome , {this.state.firstName} {this.state.lastName} !</p>