【问题标题】:Auto refresh JSON data on an set interval in React Native using React Hooks使用 React Hooks 在 React Native 中按设定的时间间隔自动刷新 JSON 数据
【发布时间】:2020-04-13 22:02:15
【问题描述】:

我正在为一个广播电台开发一个 React Native 应用程序,它显示来自 JSON url 的歌曲和艺术家信息。如何获取每分钟左右更新/获取的信息?我尝试了一些使用 setInterval 的变体,但似乎无法让它在我的功能组件中工作。我猜这是因为我试图将 setInterval 与异步函数一起使用..?提前致谢!

  const [track, setTrack] = useState({});

  async function fetchData() {
    const res = await fetch(" my API url ");
    res
      .json()
      .then(res => setTrack(res.data[0].track.title))
      .catch(err => setErrors(err));
  }
  useEffect(() => {
      fetchData();
  });
<Text>{track}</Text>

【问题讨论】:

  • 您试图从哪里检索信息?您是否考虑过网络套接字?
  • 这是服务器(Centova Cast)上的一个 json 文件,每次歌曲更改时都会更新。看起来网络套接字可能对此有好处..您可以指出我的任何资源/示例吗?

标签: javascript json reactjs react-native react-hooks


【解决方案1】:

你可以使用setTimeout在第一个组件挂载后每隔N时间请求一次,比如:

import React from 'react';

const Component = () => {
    const [track, setTrack] = React.useState('');

    React.useEffect(() => {
        let repeat;

        async function fetchData() {
            try {
                const res = await fetch(" my API url ");
                const json = await res.json();

                setTrack(json.data[0].track.title);

                repeat = setTimeout(fetchData, 60000); // request again after a minute
            } catch (error) {
                console.error(error.message)
            }
        }

        fetchData();

        return () => {
            if (repeat) {
                clearTimeout(repeat);
            }
        }
    }, []);

    return (
        <Text>{track}</Text>
    );
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 2018-12-14
    • 1970-01-01
    • 2020-10-10
    • 1970-01-01
    • 2021-11-26
    • 2019-08-25
    相关资源
    最近更新 更多