无法在 axios 回调中访问更正此 [英] Cannot access correct this inside an axios callback

查看:20
本文介绍了无法在 axios 回调中访问更正此的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有点心神不宁的自动取款机.我设法编写了以下代码,它从 url 下载一个 JSON 并将其显示在屏幕上:

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>
    )

  };
}

但是...这很奇怪,因为如果我想将接收到的json存储在状态对象的数据中,但是当我尝试这样做时,它说状态变量实际上不存在...

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...

什么意思?既然是component WILL mount函数,状态还不存在,所以我无法将接收到的数据存储在那里?

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:实际解决方案可行,但在这种情况下使用本地存储质量很低.

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

有吗

推荐答案

问题不是状态不存在,而是你没有使用正确的状态上下文.

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

你需要bindaxios回调函数,否则里面的this会引用它自己的context而不是react组件的context

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);
  })

并在渲染中

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

  };

这篇关于无法在 axios 回调中访问更正此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆