this.setState未定义

Nat*_*at8 31 reactjs react-native

我一直看到使用=>或.bind(this)的答案,但这些解决方案都没有奏效.

import React, { Component } from 'react';
import { View, Text, TextInput, StyleSheet } from 'react-native';

export default class MyWeatherApp extends Component {
  constructor(props) {
  super(props);

  this.state = {};
}

getInitialState() {
  return {
    zip: '',
    forecast: null,
  };
}

_handleTextChange(event) {
  var zip = event.nativeEvent.text;
  this.setState({zip: zip});
}
Run Code Online (Sandbox Code Playgroud)

解:

_handleTextChange = (event) => {
  var zip = event.nativeEvent.text;
  this.setState({zip: zip});
  alert('click');
}
Run Code Online (Sandbox Code Playgroud)

Dmi*_*rov 55

当你extend React.Component与ES2015类语法,你需要你的动作处理程序绑定到你的类的上下文.

试试这个: onChange={e => _handleTextChange(e)}

通常,最好不要在bind内部使用箭头函数或方法,render因为它会在任何render调用中生成函数的新副本.将函数声明移动到class constructor.

在这种情况下,我个人更喜欢使用箭头函数作为类属性

class MyClass extends React.Component {

  handleClick = () => {
    // your logic
  };

  render() {
    return (
      <button onClick={this.handleClick}>Click me</button>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

它不是ES2015规范的一部分,但是babel stage-0预设支持这种语法

您可以在本文中阅读React中有关上下文绑定的更多信息

  • @EmanuelQuimper 如果子组件是纯的,它很可能会对其 props 进行浅层相等检查,以查看它们中的任何一个是否不同,以避免在没有更改的情况下重新渲染。如果您在渲染中创建了 Lamba 方法,则每次渲染时都会创建一个新的 `onChange`,子组件将看到这个“新”属性并在不需要时重新渲染。 (2认同)

Shu*_*bib 14

让我详细说一下.因为我不得不浪费大量时间研究它,我不希望任何人重复这个...

如果你不使用箭头功能,你必须绑定this像'9'线

class MyClass extends React.Component {

  handleButtonClick(){
    console.log("Hello from here");
  };

  render() {
    return (
      <button onClick={this.handleButtonClick.bind(this)}>Click me</button>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

另一种方法是使用ES6 Arrow功能.在这种情况下,您无需绑定'this'.安装'babel stage-1预设'将支持此功能.

在项目中运行以下命令:

npm i babel-preset-stage-1 --save

你的.babelrc看起来像这样.特别是预设中的"stage-1".

{
  "presets": ["es2015", "react", "stage-1"],
  "env": {
    "development": {
      "plugins": ["react-hot-loader/babel"]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

正如我所说,你的组件将是这样的:

class MyClass extends React.Component {

      handleButtonClick = () => {
        console.log("Hello from here");
      };

      render() {
        return (
          <button onClick={this.handleButtonClick}>Click me</button>
        );
      }
    }
Run Code Online (Sandbox Code Playgroud)


MBe*_*mam 5

constructor 你也可以像这样绑定它

class MyClass extends React.Component {
  constructor(props){
    super(props);
    this.handleButtonClick = this.handleButtonClick.bind(this);
 }
  handleButtonClick(){
    console.log("Hello from here");
  }

  render() {
    return (
      <button onClick={this.handleButtonClick}>Click me</button>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)


Abd*_*sha 5

问题是:我遇到了错误:this.setState不是一个函数

给定我将函数绑定到组件构造函数中的状态,如下所示:

 this.getRequestData = this.getRequestData.bind(this);
Run Code Online (Sandbox Code Playgroud)

我的职能是:

getRequestData(){
    axios.post('http://example.com/getInfo', jsonData)
                        .then(function (res) {
                            console.log(res);
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                        this.setState({ stateVaribale });
                    })
}
Run Code Online (Sandbox Code Playgroud)

解决方案是在axios请求中使用arrow functions而不是使用keyword函数,因为在axios请求中引用功能而不是组件状态会引起混淆。

getRequestData(){
axios.post('http://example.com/getInfo', jsonData)
                        .then(res => {
                        console.log(res);
                        })
                        .catch(error => {
                            console.log(error);
                        });
                        this.setState({ stateVaribale });
                    })}
Run Code Online (Sandbox Code Playgroud)