[英]Error when using useEffect API call in React
I am calling this api inside a context provider:我在上下文提供程序中调用此 api:
const url = 'http://127.0.0.1:8000/api/posts/'
const PostListContextProvider = (props) => {
const [posts, setPosts] = useState([])
useEffect(async () => {
const {data} = await axios.get(url);
setPosts(data)
}, [posts]);
return (
<PostListContext.Provider value={ posts }>
{ props.children }
</PostListContext.Provider>
);
}
Upon consuming the context using useContext, this error occurs:使用 useContext 使用上下文时,会发生此错误:
react-dom.development.js:19710 Uncaught TypeError: destroy is not a function
What am I doing wrong?我究竟做错了什么?
ps.even though I am getting the error, I am still successfully fetching the data ps.即使我收到错误消息,我仍然可以成功获取数据
useEffect
should not be async
useEffect
不应该是async
的
Do it like this:像这样做:
useEffect(() => {
(async () => {
const {data} = await axios.get(url);
setPosts(data)
})()
}, [posts]);
useEffect
is supposed to return a function
if it returns something, since you are defining the callback function to useEffect as a promise, what it essentially returns is a promise which is not what it expects. useEffect
is supposed to return a function
if it returns something, since you are defining the callback function to useEffect as a promise, what it essentially returns is a promise which is not what it expects.
In order to use a async function within useEffect you would write it like为了在 useEffect 中使用异步 function 你可以这样写
useEffect(() => {
async function myFn() {
const {data} = await axios.get(url);
setPosts(data)
}
myFn();
}, [posts]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.