在設定來自 fetch API 的資料狀態后,我試圖將異步狀態值從父級發送到子級:
Profile.js
function Profile() {
const { id } = useParams();
const [user, setUser] = useState();
useEffect(() => {
const getUser = async () => {
const response = await fetch(`http://localhost:8000/users/${id}`);
const data = await response.json();
setUser(data);
};
getUser();
}, [id]);
return (
...
<Feed id={user._id} />
...
)
}
Feed.js
function Feed(id) {
const { user, isLoading, error } = useContext(AuthContext);
useEffect(() => {
const getPosts = async () => {
const response = id
? await fetch(`http://localhost:8000/${id}`)
: await fetch(`http://localhost:8000/home/${user._id}`);
const data = await response.json();
setPosts(data);
};
getPosts();
}, [id, userId, user._id]);
...
}
在Profile.js組件上,我通過使用可選的鏈接運算子解決了這個問題?
<div className={profileStyles.userItem}>
phone: <span>{user?.phone}</span>
</div>
但我不知道如何告訴Feed.js組件等待id屬性,所以它將為 null 并且Feed.js組件不會重新渲染,如何解決?
uj5u.com熱心網友回復:
如果你想等待用戶被獲取,你Feed只能在用戶未定義時渲染(所以它等待它被獲取):
{user && <Feed id={user._id} />
這樣,組件Feed將僅在用戶未定義時才呈現
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/442719.html
上一篇:在渲染DOM之前加載異步資料
下一篇:Angular訂閱以等待回應
