简体   繁体   中英

Accessing state from within component React Native

I'm fairly new to react native and working on an app where I use a RkButton and then update the state when the button is clicked. The code is like this.

 render() { const { user } = this.props; let navigate = this.props.navigation.navigate; let items = MainRoutes.map(function (route, index) { return ( <RkButton rkType='square' key={index} onPress={() => { this.setState({ redeem: true }); }}> </RkButton> ) }); return ( <View style={{flex: 1,}}> <ScrollView alwaysBounceVertical overScrollMode={"always"} style={{flex: 1, backgroundColor: 'white'}} refreshControl={ <RefreshControl refreshing={this.state.refreshing} onRefresh={() => this.handleRefresh()} /> } contentContainerStyle={styles.rootContainer}> {items} </ScrollView> </View> ) } 

I get 'this.setState is not a function', since I've used the code from the UIKitten library I'm not entirely familiar with it. I'm pretty sure this is something to do with either ES6 or a misunderstanding on my part of how components work.

Could someone enlighten me?

You loose the Components context here:

  // Component context
  function (route, index) {
    // Functions context

Change it to:

  (route, index) => {

The problem is that function declared with keyword function have it own context this . You need to use arrow functions to have access to parent context:

let items = MainRoutes.map((route, index) => {
  return (
    <RkButton
      rkType='square'
      key={index}
      onPress={() => {
          this.setState({
            redeem: true
          });
      }}>
    </RkButton>
  )
});

You should keep a copy of this and use it inside any other function. whenever needed, as mention in line number 3.

so your code has some minor change

render() {
    const { user } = this.props;
    let self=this;

    let navigate = this.props.navigation.navigate;

    let items = MainRoutes.map(function (route, index) {
      return (
        <RkButton
          rkType='square'
          key={index}
          onPress={() => {
              self.setState({
                redeem: true
              });
          }}>
        </RkButton>
      )
    });

      return (
        <View style={{flex: 1,}}>
            <ScrollView
              alwaysBounceVertical
              overScrollMode={"always"}
              style={{flex: 1, backgroundColor: 'white'}}
              refreshControl={
                  <RefreshControl
                  refreshing={this.state.refreshing}
                  onRefresh={() => this.handleRefresh()}
                  />
              }
              contentContainerStyle={styles.rootContainer}>
                {items}
            </ScrollView>
          </View>
      )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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