在反应中从axios调用数据会导致错误
calling data from axios in react causes error
我是 Axios 的新手,所以我想我可以将它与 React 一起使用来制作一个小型 PWA,只是为了好玩和学习它。该功能很简单,只需按下按钮即可显示信息。当我试图在 return() 中显示信息时,我收到一条错误消息,提示它无法读取 api 端点的 属性,所以我认为发生的事情是试图在调用函数之前渲染它。我认为这是 async / await 的一个很好的用途,但我不确定如何实现它。
这是代码
const IndexPage = () => {
const [data, getData] = useState([])
const options = {
method: 'GET',
url: 'https://dad-jokes.p.rapidapi.com/random/joke',
headers: {
'X-RapidAPI-Host': 'dad-jokes.p.rapidapi.com',
'X-RapidAPI-Key': '17fb7de893msh59a82cece7f697ap1c0305jsn0e7db5ca2d76'
}
};
function jokes() {
axios.request(options).then((res) => {
console.log(res.data);
const data = res.data
getData(data)
}).catch((error) => {
console.error(error);
});
}
return (
<Layout>
<main className="full-page">
<div className="center">
<cite>Press for the best dad jokes around!</cite>
<button onClick={jokes}> Get Jokes</button>
<h4>{data.body[0].setup}</h4> // this is running before function is being called onClick.
<p>{data.body[0].punchline}</p>
</div>
</main>
</Layout>
);
};
提前致谢!
const [data, getData] = useState([])
应该叫setData
。参见 https://reactjs.org/docs/hooks-state.html
首先 运行,data
设置为 []
,一个空数组。后来,
<h4>{data.body[0].setup}</h4>
您尝试从数组中读取 body[0].setup
。这一行相当于 [].body[0].setup
.
您可以在此处使用 optional chaining operator (?.
):
<h4>{data?.body?.[0]?.setup}</h4>
这将评估为 undefined
而不是抱怨“无法读取未定义的 属性”。
我是 Axios 的新手,所以我想我可以将它与 React 一起使用来制作一个小型 PWA,只是为了好玩和学习它。该功能很简单,只需按下按钮即可显示信息。当我试图在 return() 中显示信息时,我收到一条错误消息,提示它无法读取 api 端点的 属性,所以我认为发生的事情是试图在调用函数之前渲染它。我认为这是 async / await 的一个很好的用途,但我不确定如何实现它。
这是代码
const IndexPage = () => {
const [data, getData] = useState([])
const options = {
method: 'GET',
url: 'https://dad-jokes.p.rapidapi.com/random/joke',
headers: {
'X-RapidAPI-Host': 'dad-jokes.p.rapidapi.com',
'X-RapidAPI-Key': '17fb7de893msh59a82cece7f697ap1c0305jsn0e7db5ca2d76'
}
};
function jokes() {
axios.request(options).then((res) => {
console.log(res.data);
const data = res.data
getData(data)
}).catch((error) => {
console.error(error);
});
}
return (
<Layout>
<main className="full-page">
<div className="center">
<cite>Press for the best dad jokes around!</cite>
<button onClick={jokes}> Get Jokes</button>
<h4>{data.body[0].setup}</h4> // this is running before function is being called onClick.
<p>{data.body[0].punchline}</p>
</div>
</main>
</Layout>
);
};
提前致谢!
const [data, getData] = useState([])
应该叫setData
。参见 https://reactjs.org/docs/hooks-state.html
首先 运行,data
设置为 []
,一个空数组。后来,
<h4>{data.body[0].setup}</h4>
您尝试从数组中读取 body[0].setup
。这一行相当于 [].body[0].setup
.
您可以在此处使用 optional chaining operator (?.
):
<h4>{data?.body?.[0]?.setup}</h4>
这将评估为 undefined
而不是抱怨“无法读取未定义的 属性”。