javascript - 是否在本机反应中调用 setState 函数,仅在箭头函数中有效?
问题描述
我需要你的帮助来解释这个反应本机代码。
下面的代码,当使用箭头函数编写 updateState 函数时,代码可以完美运行
import React, { Component } from 'react'
import { Text, View } from 'react-native'
export default class Home extends Component {
state = {
myState: 'aaaaa'
}
updateState = () => {
this.setState({ myState: 'The state is updated' })
}
render() {
return (
<View>
<Text onPress = {this.updateState}>
UPDATE:{this.state.myState}
</Text>
</View>
);
}
}
但是当我更改 updateState 函数时,使用下面的代码这样的普通函数(不是箭头函数),按下文本时我的状态不会改变。
import React, { Component } from 'react'
import { Text, View } from 'react-native'
export default class Home extends Component {
state = {
myState: 'aaaaa'
}
updateState (){
this.setState({ myState: 'The state is updated' })
}
render() {
return (
<View>
<Text onPress = {this.updateState}>
UPDATE:{this.state.myState}
</Text>
</View>
);
}
}
我的问题是,调用 setState 函数是否必须使用箭头函数?
感谢您对此事的帮助。
谢谢
解决方案
如果你想使用没有箭头应该bind
添加constructor()
class App extends Component {
constructor(props){
super(props);
this.state = {
myState: 'aaaaa'
}
this.updateState = this.updateState.bind(this);
}
updateState(){
this.setState({ myState: 'The state is updated' })
}
render() {
return (
<View>
<Text onPress = {this.updateState}>
UPDATE:{this.state.myState}
</Text>
</View>
);
}
}
推荐阅读
- python - 使用凸壳坐标提取字符 - opencv - python
- batch-file - 密码中使用 PIPE 特殊字符时批处理脚本崩溃
- javascript - JS 脚本不改变表格行背景颜色
- google-chrome - Chrome 浏览器上的地理位置超时等待用户许可
- flutter - 颤振不反映变化
- java - Java 10:替换 java.xml.ws 冲突
- chef-infra - 厨师 - 断言注册表项存在
- selenium - 硒 - 如何找到 xpath
- javascript - 从 javascript 获取图像大小时出错
- java - java应用程序中的一个方法。哪个方法应该从Rest Api返回数据