Reactjs 如何使用react访问axios
我正在使用react创建报价生成器。我在访问数组中的对象时遇到问题。查看所有数组很好,但当我尝试指定需要哪个键时,它会说无法读取未定义的属性Reactjs 如何使用react访问axios,reactjs,object,axios,state,Reactjs,Object,Axios,State,我正在使用react创建报价生成器。我在访问数组中的对象时遇到问题。查看所有数组很好,但当我尝试指定需要哪个键时,它会说无法读取未定义的属性 class Quote extends React.Component{ state = { quotes : [] } componentDidMount(){ axios.get('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a
class Quote extends React.Component{
state = {
quotes : []
}
componentDidMount(){
axios.get('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json').then(res=>{
this.setState({
quotes: res.data.quotes
})
})
}
render(){
console.log(this.state.quotes[0])
这是正在工作的代码,它显示如下结果:
{quote: "Life isn’t about getting and having, it’s about giving and being.", author: "Kevin Kruse"}
但当我用这个代替时:
console.log(this.state.quotes[0].quote)
错误显示:
TypeError: Cannot read property 'quote' of undefined
数据在初始渲染时不可用,并在初始渲染后异步加载。您需要使用加载状态或有条件地访问该状态
class Quote extends React.Component{
state = {
quotes : []
isLoading: true,
}
componentDidMount(){
axios.get('https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json').then(res=>{
this.setState({
quotes: res.data.quotes,
isLoading: false,
})
})
}
render(){
if(this.state.isLoading) return <div>Loading...</div>
console.log(this.state.quotes[0])
类引号扩展了React.Component{
状态={
引号:[]
孤岛加载:是的,
}
componentDidMount(){
axios.get()https://gist.githubusercontent.com/camperbot/5a022b72e96c4c9585c32bf6a75f62d9/raw/e3c6895ce42069f0ee7e991229064f167fe8ccdc/quotes.json)。然后(res=>{
这是我的国家({
引号:res.data.quotes,
孤岛加载:false,
})
})
}
render(){
如果(this.state.isLoading)返回加载。。。
console.log(this.state.quotes[0])
谢谢,先生,它可以工作,只是isLoading需要为false才能表示感谢