Cannot access correct this inside an axios callbac

2020-01-29 02:24发布

问题:

got a little mind-fart atm. I've managed to write following code, which downloads a JSON from url and displays it on the screen:

export default class Appextends React.Component {

constructor(props) {
    super(props);
    this.state = {
      data: [],
    }
  }

  componentWillMount() {

    axios.get(//url//)
      .then(function (response) {
        localStorage.setItem('data', JSON.stringify(response.data));
        //this.setState({data: response.data}); -- doesnt work
      })
      .catch(function (error) {
        console.log(error);
      })
  }

  render() {
    let items = JSON.parse(localStorage.getItem('data'));
    return (
      <ul>
        {items.map(v => <li key={v.id}>{v.body}</li>)}
      </ul>
    )

  };
}

But... this is weird, because if I would like to store the received json inside the data in the state object, but when Im trying to do so, it says that the state variable doesnt exist actually...

What does it mean? Since it's component WILL mount function, the state doesnt exist yet, so thats why Im unable to store the received data there?

Is there any way to get through this? Thank you so much

P.S: Actual solution works, but it's pretty low quality, to use local storage in this case.

Is there

回答1:

The problem is not that the state doesn't exist, it is that you are not using the correct context for state.

You need to bind the axios callback function, otherwise this inside it will refer to its own context rather than that of the react component

axios.get(//url//)
  .then( (response) => {
    this.setState({data: response.data});
  })
  .catch( (error) => {
    console.log(error);
  })

and in render

render() {
    return (
      <ul>
        {this.state.data.map(v => <li key={v.id}>{v.body}</li>)}
      </ul>
    )

  };