希望您能帮助我。
请原谅我从原始文件中剥离的代码,以使您更容易理解。我会尽力解释一下,因为我对React不太熟悉。
我首先需要获取一个会话ID才能检索帖子。我的会话ID很好。
const retrieveSessionId = async () => {
try {
const response = await axios({
method: 'get',
url: 'URLGOESHERE'
})
const sessionId = response.data['session_id']
postsPullPoll = setInterval(()=> retrievePosts(sessionId), 1000);
} catch (error) {
console.log(error);
return false;
}
};
retrieveSessionId();
然后,我需要使用该会话ID来检索我的帖子。首先,它返回状态 202 ,在此API中表示已创建会话,但我必须继续轮询才能获得状态 200 。因此,我使用了 setInterval 来轮询帖子,然后返回状态 200 ,一旦发生,我的帖子就会变好。
const retrievePosts = async (sessionId) => {
try {
const response = await axios({
method: 'get',
url: 'URLGOESHERE'
})
const postsPullStatus = response.status
if(postsPullStatus == 202) { // created session
if(postsPullPollCounter >= 50){
clearInterval(postsPullPoll);
}
postsPullPollCounter++;
}else {
console.log(postsData)
setPostPullStatus({posts: postsData, isLoading: false});
clearInterval(postsPullPoll);
}
} catch (error) {
console.log(error);
return false;
}
};
然后我需要将这些帖子输出到我的HTML,因此我首先需要将它们存储在状态中。但是,当我尝试设置状态时,我的 clearInterval 突然停止工作,并且即使它得到了 200 且即使我有我的 clearInterval,该间隔仍继续(如果不是 202 。
)。在API提取我的数据时,我还处于isLoading状态,以明显在HTML中显示其他内容。
我尝试使用 UseRef 和 UseEffect ,但是我可以想象这是否是我使用不正确的解决方案。
我希望这是有道理的。这是帮助您的完整代码:
import React, { useState, useContext, useRef, useEffect } from 'react'
import axios from 'axios';
export default () => {
const { isLoading, posts } = useState({});
const [postPullStatus, setPostPullStatus] = useState({
posts: [],
isLoading: true
});
let postsPullPoll = '',
postsPullPollCounter = '';
const retrieveSessionId = async () => {
try {
const response = await axios({
method: 'get',
url: 'URLGOESHERE'
})
const sessionId = response.data['session_id']
postsPullPoll = setInterval(()=> retrievePosts(sessionId), 1000);
} catch (error) {
console.log(error);
return false;
}
};
retrieveSessionId();
const retrievePosts = async (sessionId) => {
try {
const response = await axios({
method: 'get',
url: 'URLGOESHERE'
})
const postsPullStatus = response.status
if(postsPullStatus == 202) { // created session
if(postsPullPollCounter >= 50){
clearInterval(postsPullPoll);
}
postsPullPollCounter++;
}else {
console.log(postsData)
setPostPullStatus({posts: postsData, isLoading: false});
clearInterval(postsPullPoll);
}
} catch (error) {
console.log(error);
return false;
}
};
return (
<div>
{!isLoading ? (
posts.map(post => {
<span>{post.title}</span>
})
) : (
<p>Loading...</p>
)}
</div>
);
};