【问题标题】:React Native "this.setState is not a function"React Native “this.setState 不是函数”
【发布时间】:2016-10-05 18:51:46
【问题描述】:

我开始使用 react native 并尝试将一些操作绑定到类方法,但我收到一些关于未找到方法的错误。

我试过绑定:

class AccountsScreen extends Component {
  constructor (props) {
    super(props)
    this.userChange = this.userChange.bind(this)
    this.state = {
      user: '',
      password: ''
    }
  }
  render () {
    return (
      <View>
      <Text>Pass</Text>
      <TextInput
          onChange={this.userChange}
      />
      </View>
    )
  }
  userChange (user) {
    this.setState({user: user})
  }
}

和箭头函数

class AccountsScreen extends Component {
  constructor (props) {
    super(props)
    this.state = {
      user: '',
      password: ''
    }
  }
  render () {
    return (
      <View>
      <Text>Pass</Text>
      <TextInput
          onChange={(user) => this.userChange(user)}
      />
      </View>
    )
  }
  userChange (user) {
    this.setState({user: user})
  }
}

但我不断收到同样的错误:

“this.setState 不是函数”

完全卡住了。有什么想法吗?

【问题讨论】:

  • this.userChange = this.userChange.bind(this) 我猜你还是需要绑定,看看两个构造函数的区别
  • 你还在纠结吗?

标签: javascript binding react-native


【解决方案1】:

其实不需要做一个函数来设置你的状态,你可以这样做

&lt;TextInput onChangeText={(user) =&gt; this.setState({user: user})} /&gt;

【讨论】:

    【解决方案2】:

    其实这是一个愚蠢的错误。我使用的是 onChange 而不是 onChangeText 方法....

    【讨论】:

    • 然后我们可以关闭问题或者你可以删除它。
    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多