参见英文答案 > How to access the correct `this` inside a callback? 10个
得到了一点心灵放屁.我设法编写以下代码,从URL下载JSON并将其显示在屏幕上:
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存储在状态对象的数据中,但是当我试图这样做时,它说状态变量实际上并不存在……
这是什么意思?既然它是组件WILL mount功能,那么状态还不存在,那就是为什么Im无法存储接收到的数据呢?
有没有办法解决这个问题?非常感谢
P.S:实际解决方案有效,但在这种情况下使用本地存储的质量相当低.
在那儿
解决方法:
问题不在于状态不存在,而是您没有使用正确的状态上下文.
你需要绑定axios回调函数,否则它内部将引用它自己的上下文而不是react组件的上下文
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>
)
};
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!