React Native:this.setState不是函数 [英] React Native: this.setState is not a function

查看:148
本文介绍了React Native:this.setState不是函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里看到了很多关于同一问题的问题,但它似乎与我遇到的问题无关,而且有点复杂。

I see a number of questions on here relating to this same issue, but it seems none match the issue I'm having, and are a bit more complex.

我正在学习ReactJS和React Native。我正在阅读并遵循Learning React Native一书中的代码示例: https ://github.com/bonniee/learning-react-native

I am in the process of learning ReactJS and React Native. I'm in the midst of reading and following the code examples from "Learning React Native" book here: https://github.com/bonniee/learning-react-native

出于某种原因,当handleTextChange函数是函数时,在下面的代码中调用this.setState调用,导致this.SetState不是函数。错误。我的问题是为什么?与关于同一问题的其他问题不同,我不相信我对this.stateState的调用隐藏在回调函数或if语句中。为什么不定义?

For some reason, calling this.setState in the code below when the handleTextChange function is called, causes the "this.SetState is not a function." error. My question is why? Unlike other questions about this same issue, I don't believe my call to this.stateState is buried in a callback function or if statement. Why is it undefined?

这是我的代码:

class WeatherProject extends Component {
  constructor(props) {
    super(props);
    this.state = {
      zip: "",
      forecast: null
    };
  }

  _handleTextChange(event) {
    this.setState({zip: event.nativeEvent.text});
  }

    render() {
    return (
      <View style={styles.container}>
      <Text style={styles.welcome}>
      You input {this.state.zip}.
      </Text>
      <TextInput
      style={styles.input}
      onSubmitEditing={this._handleTextChange}/>
      </View>
    );
  }
}


推荐答案

不要在渲染中使用bind。 bind是一个相当昂贵的操作,应该只发生一次。你有两个选择:

Do not use bind inside a render. bind is a rather expensive operation and should only happen once. you have two options:

绑定构造函数中的函数:

either bind the function in the constructor:

this._handleTextChange = this._handleTextChange.bind(this);

或使用箭头功能:

onSubmitEditing={(e) => this._handleTextChange(e)} />

修改

显然渲染中的箭头函数也是一种不好的做法(在下面的评论和答案中向Adam Terlson致谢)。你可以阅读 eslint docs 表示:

Apparently arrow functions inside render is also a bad practice (Thx to Adam Terlson in the comments and answer below). You can read eslint docs which states:


JSX道具中的绑定调用或箭头函数将在每个渲染上创建一个全新的函数。这对性能不利,因为它会导致垃圾收集器的调用方式超出必要的范围。

A bind call or arrow function in a JSX prop will create a brand new function on every single render. This is bad for performance, as it will result in the garbage collector being invoked way more than is necessary.

使用箭头函数显然没有使用bind那么糟糕,但是应该避免。

Using arrow functions is obviously not as bad as using bind, but nevertheless should be avoided.

这篇关于React Native:this.setState不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆