問題描述
為什麼在使用 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
另外一件事,如果我們在上面的代碼中最初將它設置為 true
或 false
,useEffect
仍然運行相同,屏幕上的結果也將相同。那麼,為什麼是 true
?這是某種標準嗎?
參考解法
方法 1:
The value you pass when initializing state is up to you.
If you want it to be initialized as true you pass true like this.
const [isLoading, setIsLoading] = useState(true)
If you want you can also pass false and it will be initialized as false
const [isLoading, setIsLoading] = useState(false)
方法 2:
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
More info: https://reactjs.org/docs/handling‑events.html
方法 3:
You are asking about the reason that you did set this initial value yourself :)
Most certainly you copied that code from somewhere and the reason the isLoading
's initial state is set to true
is that your whole component actually is in such state initially and then you set it to false after fetched data is ready.
(by user13618351、Shmili Breuer、Stanley Pierre Louis、k‑wasilewski)