繁体   English   中英

在本机反应中调用 setState function 是否仅在箭头 function 中有效?

[英]Does call to setState function in react native, only works in arrow function?

我需要你的帮助来解释这个反应本机代码。

下面的代码,当使用箭头 function 编写 updateState function 时,代码工作正常

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 function,使用普通的function(不是箭头功能),如下面的代码,我的state在按下文本时不会改变。

    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 function 是否必须使用箭头 function?

感谢您对此事的帮助。

谢谢

如果你想使用没有箭头应该在constructor()中添加bind

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>
   );
  }
}

如果要使用function ,则需要在构造函数中绑定this ,以便 function updateState在引用this引用 class 。 尝试以下操作:

constructor() {
  this.updateState = this.updateState.bind(this);
}

希望这会有所帮助!

在每次渲染时,都会创建对 function 的引用。

因此,为避免这种情况,使用绑定 OR 箭头 function。

我这样称呼 function :

函数A = () => {}

TouchableOpacity onPress={()=> this.functionA()}

暂无
暂无

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

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