我有以下代码(见下文)
我希望它显示由firstName和lastName组成的用户名。为什么下面的代码不起作用?
我希望它显示
欢迎Daggie Blanqx!
class Header extends React.Component{
constructor(props){
super(props);
this.state = {
firstName : 'Daggie',
lastName : 'Blanqx',
userName : ()=>(this.state.firstName + this.state.lastName)
}
}
render(){
return(
<div>
<p> Welcome {this.state.userName} !</p>
</div>
)
}
}
答案 0 :(得分:4)
您缺少()
<p> Welcome {this.state.userName()} !</p>
也无需为此定义函数直接获得这样的结果
<p>Welcome , {this.state.firstName} {this.state.lastName} !</p>
答案 1 :(得分:2)
似乎您正在向状态插入一个函数,因此您需要调用它来获取结果。通常不建议将这样的功能置于状态。但是,如果您仍然想使用该方法,请尝试以下操作:
<table>
<thead>
<tr>
<th>c1</th>
<th>c2</th>
<th>c3</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td><td>t</td><td>p</td>
</tr>
<tr>
<td>a</td><td>v</td><td>r</td>
</tr>
<tr>
<td>f</td><td>a</td><td>d</td>
</tr>
<tr>
<td>h</td><td>t</td><td>i</td>
</tr>
</tbody>
</table>
一种更好的方法是从状态中删除该函数并执行以下操作:
<p>Welcome , {this.state.userName()} !</p>
然后在您的模板中:
getUserName() {
return this.state.firstName + this.state.lastName
}
答案 2 :(得分:1)
在您的示例中,您正在访问函数this.state.userName
,您需要像这样this.state.userName()
进行调用
this.state.userName
将返回function
变量,您需要将()
放在函数末尾,以获取函数的return
值
你知道为什么它不起作用
尝试避免在状态对象中使用方法
答案 3 :(得分:1)
它应该引发错误,因为您试图与状态进行交互,但是状态尚未初始化。为此,请使用componentDidMount()
+ prevState
或将其放在render()
内:
变体1 :
import React, { Component } from 'react'
export default class Header extends Component {
constructor(props) {
super(props)
this.state = {
firstName : 'Daggie',
lastName : 'Blanqx'
}
}
render() {
return(
<div>
<p> Welcome {this.state.firstName + this.state.lastName} !</p>
</div>
)
}
}
变体2 :
import React, { Component } from 'react'
export default class Header extends Component {
constructor(props) {
super(props)
this.state = {
firstName : 'Daggie',
lastName : 'Blanqx',
fullName: ''
}
}
componentDidMount() {
this.setState(prevState => ({
fullName: prevState.firstName + prevState.lastName
}))
}
render() {
return(
<div>
<p> Welcome {this.state.fullName} !</p>
</div>
)
}
}