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

Why the initial loading state is set to true while using useState?

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

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

另一件事,如果我们在上面的代码中最初将它设置为 truefalseuseEffect 仍然运行相同,屏幕上的结果也将是相同。那么,为什么 true?这是某种标准吗?

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

如果你想让它初始化为 true,你可以像这样传递 true。

const [isLoading, setIsLoading] = useState(true)

如果你想你也可以传false,它会被初始化为false

const [isLoading, setIsLoading] = useState(false)
  const [isLoading, setIsLoading] = useState(true)
  const [themes, setThemes] = useState([])

  useEffect(() => {
    const fetchThemes = async () => {
      try {
        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

更多信息:https://reactjs.org/docs/handling-events.html

你问的是你自己设置这个初始值的原因:)

您肯定是从某处复制了该代码,isLoading 的初始状态设置为 true 的原因是您的整个组件最初实际上处于这种状态,然后您设置了它获取数据准备就绪后为 false。