React钩子不会更新值

时间:2019-12-18 18:59:47

标签: reactjs

我有一个简单的Loader组件,该组件在我的本地应用程序中执行异步操作时显示。

代码如下:

import React, {useRef} from "react";
import { View, Text} from "react-native";

export default function StatusBar(props){
  const INITIAL_STATE = 'Waiting'
  const FINAL_STATE = 'Waiting...'
  const DURATION = 800

  const {loading} = props
  const [loader, setLoader] = React.useState(INITIAL_STATE)
  const id = useRef(null)

  React.useEffect(() => {
    id.current = setInterval(() => {
      console.log(loader)
      if (loader != FINAL_STATE) {
        setLoader(loader => loader + '.')
      } else {
        setLoader(INITIAL_STATE)
      }
    }, DURATION)

    return () => {
      clearTimeout(id.current)
    }
  }, [])

  return (
    <>
      {loading && 
        <View>
          <Text>{loader}</Text>
        </View>
      }
    </>
  )
}

问题在于console.log总是返回相同的值:“ Waiting”,这很奇怪,因为在屏幕上我可以看到它为等待添加了无限点。 如何通过return方法中的{loader}与从console.log打印的结果之间的不匹配?我在做什么错了?

0 个答案:

没有答案
相关问题