为什么使用 useState 时初始加载状态设置为 true?

2 javascript reactjs react-hooks use-effect use-state

我很困惑为什么该标志在初始状态下isLoading设置为true 。不是说一开始就应该是假的吗?考虑这个简单的例子:

const SearchCharity = () => {
  const [isLoading, setIsLoading] = useState(true)
  const [themes, setThemes] = useState([])

  useEffect(() => {
    const fetchThemes = async () => {
      try {
        setIsLoading(true)

        const result = await axios.get(url)
        setThemes(result.data.themes.theme)

        setIsLoading(false)
      } catch (err) {
        console.log(err)
      }
    }
    fetchThemes()
  }, [])

  return (
      {
        isLoading ? <h1>Loading......</h1> : <h1>Display Content</h1>
      }
    )

export default SearchCharity
Run Code Online (Sandbox Code Playgroud)

另一件事是,如果我们在上面的代码中将其设置为true或,则仍然运行相同,屏幕上的结果也将相同。所以为什么?这是某种标准吗?falseuseEffecttrue

Shm*_*uer 5

初始化状态时传递的值由您决定。

如果你希望它被初始化为true,你可以像这样传递true。

const [isLoading, setIsLoading] = useState(true)
Run Code Online (Sandbox Code Playgroud)

如果你愿意,你也可以传递 false ,它将被初始化为 false

const [isLoading, setIsLoading] = useState(false)
Run Code Online (Sandbox Code Playgroud)