有了一个有点烦人的提款机。我设法编写了以下代码,该代码从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挂载 功能,因此状态尚不存在,所以这就是为什么我无法将接收到的数据存储在那里的原因?
有什么办法可以解决这个问题?非常感谢
PS :在这种情况下,使用本地存储是可行的解决方案,但是质量很低。
在那儿
问题不是状态不存在,而是您没有使用正确的状态上下文。
您需要bind使用axios callback function,否则其this内部将引用其自身的上下文,而不是react组件的上下文
bind
axios callback function
this
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> ) };