Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/389.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何每隔一定时间不断刷新react组件_Javascript_Reactjs - Fatal编程技术网

Javascript 如何每隔一定时间不断刷新react组件

Javascript 如何每隔一定时间不断刷新react组件,javascript,reactjs,Javascript,Reactjs,这个问题与加载和获取有很大关系。所以我有一个从API加载注释的react组件 function App (){ const [com, setCom] = useState([]) const [isLoading, setLoading] = useState(true) useEffect(() =>{ fetch('https://jsonplaceholder.typicode.com/comments?postId=5').the

这个问题与加载和获取有很大关系。所以我有一个从API加载注释的react组件

function App (){

    const [com, setCom] = useState([])

    const [isLoading, setLoading] = useState(true)


    useEffect(() =>{

        fetch('https://jsonplaceholder.typicode.com/comments?postId=5').then(ddd => ddd.json())
        .then(data => {


             setCom(data)

            setLoading(false)
        })
    })
    
    const coms = com.map(data => <h3>{data.body} <br/></h3>)

    if(isLoading){

        return <h1>Loading</h1>
    }
    else if(isLoading === false){
        return (

            <div className="con">
                {coms}
            </div>
        )
    }
}
函数应用程序(){
const[com,setCom]=useState([])
常量[isLoading,setLoading]=useState(真)
useffect(()=>{
取('https://jsonplaceholder.typicode.com/comments?postId=5)。然后(ddd=>ddd.json()
。然后(数据=>{
setCom(数据)
设置加载(错误)
})
})
const coms=com.map(数据=>{data.body}
) 如果(孤岛加载){ 回装 } else if(isLoading==false){ 返回( {coms} ) } }
因此,在这个组件中,我有两种状态,一种是存储注释,另一种是存储加载值,在
useffect
中获取状态后,加载值将发生变化

这段代码的问题是,假设服务器宕机或我的internet断开,即使它返回,该组件将永远停留在加载阶段,直到用户手动刷新页面。那么,如何让组件重新获取数据,或者只是刷新组件


提前感谢您

您可以使用
setInterval()
每隔一秒或需要多长时间使用获取的数据更新状态。以下是一个例子:

const [fetchedData, setFetchedData] = useState(/* data type */);
setInterval(() => setFetchedData(/* call to the method */), 1000);
这样,组件将每秒获取数据并重新呈现组件


但请记住,只有当您知道您将每隔一段时间获得一次更新时,才应该使用此选项。如果您正在无用地重新呈现和重新获取数据,这将是对性能的持续阻碍。

以下是有关如何处理上述逻辑的一些改进

    function App() {
      const [com, setCom] = useState([]);
      const [isLoading, setisLoading] = useState(false); //Set initial value to false to avoid your component in loading state if the first call fails
      const refreshTime = 2000 //How frequently you want to refresh the data, in ms
      
      const fetchComments = async () => {
        setisLoading(true) //set to true only when the api call is going to happen
        const data = await fetch('https://jsonplaceholder.typicode.com/comments?postId=5').then(ddd => ddd.json()).then(data => {
          if(Array.isArray(data)) setCom(data);
        })
        setisLoading(false); //make sure to set it to false so the component is not in constant loading state
      }
      
      useEffect(() => {
        const comInterval = setInterval(fetchComments, refreshTime); //This will refresh the data at regularIntervals of refreshTime
        return () => clearInterval(comInterval) //Clear interval on component unmount to avoid memory leak
      },[])
      
      const coms = com.map(data => <h3>{data.body} <br/></h3>)
      if(isLoading){

            return <h1>Loading</h1>
        }
        else if(isLoading === false){
            return (

                <div className="con">
                    {coms}
                </div>
            )
        }
    }
函数应用程序(){
const[com,setCom]=useState([]);
const[isLoading,setisLoading]=useState(false);//将初始值设置为false,以避免在第一次调用失败时组件处于加载状态
const refreshTime=2000//刷新数据的频率,单位为毫秒
const fetchComments=async()=>{
setisLoading(true)//仅当api调用即将发生时才设置为true
常量数据=等待获取('https://jsonplaceholder.typicode.com/comments?postId=5)。然后(ddd=>ddd.json())。然后(data=>{
if(Array.isArray(数据))setCom(数据);
})
setisLoading(false);//确保将其设置为false,使组件不处于恒定加载状态
}
useffect(()=>{
const comInterval=setInterval(fetchComments,refreshTime);//这将以refreshTime的正则间隔刷新数据
return()=>clearInterval(comInterval)//卸载组件时清除间隔以避免内存泄漏
},[])
const coms=com.map(数据=>{data.body}
) 如果(孤岛加载){ 回装 } else if(isLoading==false){ 返回( {coms} ) } }
解决了这个问题,而无需编写大量逻辑。该包完全是为您的用例而设计的。您可以将
setLoading
放在
finally
块中,而不是
then
块中
fetch()。然后(setCom)。最后(()=>setLoading(false))