簡體   English   中英

this.setState 未定義

[英]this.setState is undefined

我一直看到答案說使用 => 或 .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});
}

解決方法:

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

當您使用 ES2015 類語法extend React.Component ,您需要將操作處理程序綁定到類的上下文。

試試這個: onChange={e => _handleTextChange(e)}

通常,最好不要在render使用箭頭函數或bind方法,因為它會在任何render調用中生成函數的新副本。 將函數聲明移至class constructor

在這種情況下,我個人更喜歡使用箭頭函數作為類屬性

class MyClass extends React.Component {

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

  render() {
    return (
      <button onClick={this.handleClick}>Click me</button>
    );
  }
}

它不是 ES2015 規范的一部分,但babel stage-0 預設支持這種語法

您可以在本文中閱讀有關 React 中上下文綁定的更多信息

讓我詳細寫一下。 因為我不得不浪費很多時間來研究它&我不希望任何人重復這個......

如果你不使用箭頭函數,你必須像 Line '9' 一樣綁定this

class MyClass extends React.Component {

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

  render() {
    return (
      <button onClick={this.handleButtonClick.bind(this)}>Click me</button>
    );
  }
}

另一種方法是使用 ES6 箭頭函數。 在這種情況下,您不需要綁定“this”。 安裝 'babel stage-1 preset' 將支持這一點。

在您的項目中運行以下命令:

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

你的 .babelrc 看起來像這樣。 特別是預設中的“stage-1”。

{
  "presets": ["es2015", "react", "stage-1"],
  "env": {
    "development": {
      "plugins": ["react-hot-loader/babel"]
    }
  }
}

正如我所說,您的組件將是這樣的:

class MyClass extends React.Component {

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

      render() {
        return (
          <button onClick={this.handleButtonClick}>Click me</button>
        );
      }
    }

問題是:我有那個錯誤:this.setState is not a function

鑒於我將我的函數綁定到組件構造函數中的狀態,如下所示:

 this.getRequestData = this.getRequestData.bind(this);

我的功能是:

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

解決方案是在 axios 請求中使用arrow functions而不是使用keyword function,導致在 axios 請求中引用函數而不是組件 state會造成混淆。

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

你也可以像這樣在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>
    );
  }
}

在 react native 中,我們在使用 axios 時遇到了這個錯誤,例如

    componentDidMount(){
    axios.get('https://the request url')
    .then( function(response) {
      this.setState({products:response.data.products});
    })
    .catch(function(error) {
      console.log(error);
    })
}

如果我們這樣嘗試,我們會得到:

undefined 不是一個對象(評估'this.setState')

那么我們如何解決這個問題,我們可以使用這樣的箭頭函數來解決它

componentDidMount(){
        axios.get('https://the request url')
        .then( (response)=> {
          this.setState({products:response.data.products});
        })
        .catch((error)=> {
          console.log(error);
        })
    }

這將解決問題,希望這會有所幫助

您需要綁定您的操作,否則您會在瀏覽器中看到名為 undefined 的錯誤 有三種方法可以綁定您的操作

  1. 在渲染方法 this.chngHandler.bind(this) 中綁定處理程序

例如-

export class EventBind extends Component{
constructor(){
    super()
    this.state = {
        msg:'hello'
    }
}
chngHandler(){
    this.setState({
         msg:'Good bye'
    })
}
render(){
    return(
        <div>
            {this.state}
            <button onClick={this.chngHandler.bind(this)}>click</button>
        </div>
    )
 } }
  1. render ()=>this.EventHandler()箭頭函數方法

例如——

export class EventBind extends Component{
constructor(){
    super()
    this.state = {
        msg:'hello'
    }
}
chngHandler(){
    this.setState({
         msg:'Good bye'
    })
}
render(){
    return(
        <div>
            {this.state}
            <button onClick={()=>this.chngHandler()}>click</button>
        </div>
    )
}}`

3.在構造函數中綁定事件處理程序this.EventHandler = this.EventHandler.bind(this)例如-:

export class EventBind extends Component{
constructor(){
    super()
    this.state = {
        msg:'hello'
    }
    this.chngHandler = this.chngHandler.bind(this)
}
chngHandler(){
    this.setState({
         msg:'Good bye'
    })
}
render(){
    return(
        <div>
            {this.state}
            <button onClick={this.chngHandler}>click me </button>
        </div>
    )
}}

因為綁定在構造函數中發生一次,這比渲染方法中的綁定更好

第三種方法也可以這樣做 - :

export class EventBind extends Component{
constructor(){
    super()
    this.state = {
        msg:'hello'
    }
    this.chngHandler = this.chngHandler.bind(this)
}
// chngHandler(){
//     this.setState({
//          msg:'Good bye'
//     })
// }
chngHandler = ()=>{
    this.setState({
        msg:'Good Bye'
    })
}
render(){
    return(
        <div>
            {this.state}
            <button onClick={this.chngHandler}>click me </button>
        </div>
    )
}}

當您在調用另一個函數的方法中使用粗箭頭函數時,也適用於 react-native。 例如.then((response) => { this.setState({....}) }

每當您在像 axios 請求這樣的 api 調用中使用 this 時,在某些情況下,您的“this”上下文仍未定義。 在這里詳細說明其中的一些-:

`

import react from 'React'
class Test extends from React.Component {
constructor() {
super();
this.state = {
data: '',
error: ''
}
}
componentDidMount() {
url = 'http://abc.go.com';
axios.get(url).then(function(resposne) {   // Everything fine till now
this.setState({ data: response });   //Oops this context is undefined
}
).catch(function(err) {
 this.setState({ error: err });       // again this context remains to be undefined
});
}
render() {
return ( <div>this.state.data</div> ) 
}
}`

當你運行上面的代碼時,你肯定會得到一個類型錯誤,比如 setState of undefined 被調用,類似的東西。

你怎么能解決這個問題? 您可以采用兩種方法來解決這種特定類型的問題:

第一個是您可以在函數內定義一個變量,您將在其中調用 api 並為其分配“this”的值,然后您可以從該變量中引用您的狀態對象。

import react from 'React'
class Test extends React.Component
{
  constructor() { 
     super();
     this.state = {
       data: '',
       error: ''
  };
  componentDidMount() {
   let url = 'http://abc.go.com';
   currentContext = this;   // variable to be assigned this context
   axios.get(url).then(function(resposne) {   // Everything fine till now
   currentContext.setState({ data: response });   //Oops this context is undefined
   }
   ).catch(function(err) {
  currentContext.setState({ error: err });       // again this context remains to be undefined
 });
  }
 render() {
  return ( <div>this.state.data</div> ) 
 }
 }

您可以使用的第二種方法是在 axios 中定義箭頭函數,如下所示

axios.get(url).then((response) => {
  this.setState({ data: response })     //will always be bound to the this context
}) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM