用setInterval反应本机不更新useState

时间:2020-03-15 19:34:34

标签: react-native jsx

根据返回的查询结果,L01始终应为是或否。它以“否”开始,然后在检查查询后立即收到“是”。但是,即使返回的View的setLevel01值在控制台日志中清楚地显示“是”,我的返回视图也不会更新为“是”。有什么想法吗?

function DashScreen() {
let [L01, setLevel01 ] = useState('No');

useEffect(() => {
    const timer = setInterval(() => (
    setLevel01 = data.getlevels[0].level01,
    console.log("inside: ",setLevel01)
  ), 1000);
    return () => {
      clearInterval(timer);
    }
});

const { loading, error, data } = useQuery(GetLevelsQuery)

   if (loading) return 'Loading...'
   if (error) return 'Something Bad Happened'
   console.log("outside: ",L01);

  return (
      <View><Text>{L01}</Text></View>
  );}

1 个答案:

答案 0 :(得分:1)

setLevel01是用于设置新状态值的函数。试试这个:

function DashScreen() {
    const [L01, setLevel01 ] = useState('No');

    useEffect(() => {
        const timer = setInterval(() => (
            setLevel01(data.getlevels[0].level01)
        ), 1000);

        return () => {
          clearInterval(timer);
        }
    });

    const { loading, error, data } = useQuery(GetLevelsQuery)

    if (loading) {
        return <Text>'Loading...'</Text>;
    }

    else if (error) {
        return <Text>'Something Bad Happened'</Text>;
    }

    return (
        <View>
            <Text>{L01}</Text>
        </View>
    );
}