简体   繁体   中英

React error - Cannot read property 'setState' of undefined

Below code returns an error for me Uncaught (in promise) TypeError: Cannot read property 'setState' of undefined

I am new to react and this seems very basic. Any suggestion what could I be doing wrong. From the json result I want to store all names in my array.

import React, { Component } from "react";

class Search extends Component {
  constructor(props) {
  super(props);
  this.state = {
    list: [],
  }
}

Search() {

  fetch("http://url/getSearchResults")
    .then(res => res.json())
    .then(
      (res) => {

        this.setState({
          list: res.data.name
     })
  })
}

This is a very common problem with classes in React - there are two ways to solve this problem:

  1. Bind your methods in the constructor:
constructor(props) {
  super(props);

  this.state = {
    list: [],
  }

  this.Search = this.Search.bind(this);
}
  1. Use an arrow function instead:
search = () => { ... }

See this post for more information.

Note : using componentDidMount() will be useful if you are trying to make the fetch call on mount - the answer above addresses the issue of this being undefined as per the error you are seeing.

Add componentDidMount() to Search() , it is invoked immediately after a component is mounted (inserted into the tree). Initialization that requires DOM nodes should go here.Its a good place to load data from a remote endpoint.

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