首页 > 解决方案 > 是否在本机反应中调用 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 函数是否必须使用箭头函数?

感谢您对此事的帮助。

谢谢

标签: javascriptnode.jsreactjsreact-native

解决方案


如果你想使用没有箭头应该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>
   );
  }
}

推荐阅读