基本上,我需要根據異步設定的狀態來渲染組件,默認狀態為“false”,因此組件會掛載并拋出與 false 選項對應的回傳,但它不會等待更新的前提國家。
export const LayoutValidator=({children})=>{
const [auth,setAuth] = useState(undefined)
const {token} = JSON.parse(localStorage.getItem("loggedUser")||'{}');
fetch(`${urlValue}/api/validate-token`,{
method:"POST",
headers:{
authorization: token,
}
})
.then(ans=>ans.json())
.then(ans=>setAuth(ans.auth))
.catch(err=>console.log(err))
return auth ? children : <Navigate to="/" />
}
如何將此組件設定為在回傳其答案之前等待前提?
uj5u.com熱心網友回復:
您可以創建自定義的“獲取掛鉤”,然后您可以獲取資料并設定加載狀態:
const { useEffect, useState } = React
const useFetchUsers = () => {
const [users, setUsers] = useState([])
const [loading, setLoading] = useState(false)
useEffect(() => {
setLoading(() => true)
// setTimeout added to emphasize async nature
setTimeout(() => {
fetch('https://jsonplaceholder.typicode.com/users/')
.then(response => response.json())
.then(json => setUsers(() => json))
.finally(setLoading(() => false))
}, 1000)
}, [])
return {
users,
loading,
}
}
const UserItem = ({ id, name, username, email }) => {
return (
<div>
{name} - {username} - {email}
</div>
)
}
const App = () => {
const { users, loading } = useFetchUsers()
return (
<div>
{
!loading
? users.map((user) => {
return (
<UserItem
key={user.id}
{...user}
/>
)
})
: "Loading users..."
}
</div>
)
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
<script crossorigin src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<div id="root"></div>
uj5u.com熱心網友回復:
好的,所以這并不像我想象的那么微不足道(至少對我來說),非常感謝@Bergi 和@muka.gergely 以及幫助我??獲得最終解決方案的該資源的作者:https://www.debuggr。 io/react-update-unmounted-component/
這是我帶來的:
export const LayoutValidator=({children})=>{
const {invalid, auth} = useFetchToken()
return !invalid ? <Intermediate children={children}/> : <Navigate to="/" />
}
function Intermediate ({children}) {
const {invalid, auth} = useFetchToken()
return !auth ? <SplashScreen/> : children
}
function useFetchToken() {
const { token } = JSON.parse(localStorage.getItem("loggedUser") || '{}')
const [invalid, setInvalid] = useState(false)
const [auth, setAuth] = useState(false)
useEffect(()=>{
let mounted = true
setInvalid(() => true)
fetch(`${urlValue}/api/validate-token`, {
method: "POST",
headers: {
authorization: token,
}
})
.then(ans => ans.json())
.then(ans => mounted && setAuth(()=>ans.auth))
.catch(err => console.log(err))
.finally(setInvalid(()=>false))
return () => mounted = false;
},[])
return {invalid, auth}
}
在我的情況下,它運行良好,希望這對將來的某人有所幫助。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/410863.html
標籤:
