<分区>
有一个有点脑残的自动取款机。我设法编写了以下代码,它从 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 存储在状态对象的数据中,但是当我尝试这样做时,它说状态变量实际上不存在...
这是什么意思?由于它是component WILL mount 函数,状态还不存在,所以这就是为什么我无法将接收到的数据存储在那里?
有什么办法可以解决这个问题吗?非常感谢
P.S:实际解决方案有效,但质量很低,在这种情况下使用本地存储。
有没有