![](/img/trans.png)
[英]Proper way to render content without flickering ? React + Redux + TS
[英]React - Proper way to update content in render
通常,我對ReactJS的原理和渲染動態內容很有信心。 我確實可以提供一些幫助。
問題始於我有一個稱為Feed的頁面。 該供稿應顯示從API提取的圖像列表。
我需要通過作為標頭傳遞的令牌來保護此API。
在App.js中,這是代碼的相關部分,該部分檢查用戶是否登錄並限制對feed的訪問,除非他們登錄。 令牌將保存為狀態並作為道具傳遞到Feed中。
authenticate = () => {
const token = localStorage.getItem("token");
validateToken(token)
.then(() => {
this.setState({ authenticated: true, token: token });
})
.catch(() => {
this.setState({ authenticated: false, token: false });
})
}
render() {
let privateRoutes = null;
if (this.state.authenticated) {
privateRoutes =(
<div>
<Route exact path="/feed"
render={(props)=>{
return (
<Feed token={this.state.token}/>)}} />
<Route exact path="/profile/:username"
render={(props)=>{
return (
<Profile data={props}/>)}} />
</div>
);
}
然后,在Feed中,我調用API以獲取通過此令牌傳遞的圖像。 這是問題所在,在Feed中,當我控制台登錄“ this.props.token”時,在從app.js發送來的消息之前的一瞬間它為null。
這意味着我無法在componentDidMount中調用API,因為令牌最初為null。 此外,這意味着我此時無法像在render()中那樣設置帖子的狀態。
這是供稿代碼:
render() {
const token = this.props.token;
let posts = []; // should be updated by below
if (token !== false) {
loadFeedForUser(token).then((response) => {
posts = response;
console.log(posts); // logs successfully
})
.catch(() => {
posts = [];
})
}
return (
<div className="App">
<div className="content">
<div className="feed">
{ Object.values(posts).map((post, i) => {
console.log(post);
return (
<Post/> // This does not run as posts still empty array
)
})}
在HTML中,for循環的對象永遠不會運行,因為posts數組為空,因為它尚未注冊為由API更新。
我這里的架構有什么問題? 一點感覺都不好。
謝謝。
有人可以建議我可以改善這一點嗎? 我僅需要通過身份驗證時才通過app.js傳遞令牌,然后獲取所有圖像。
道具准備就緒之前,組件已安裝。 這是一個非常常見的情況,這是為什么我更喜歡鈎子的重要原因。 要修復它,您應該使用componentDidUpdate
生命周期方法,例如
componentDidUpdate(prevProps, prevState, snapshot) {
if (props.token && props.token !== prevProps.token) {
makeApiCall(props.token)
}
}
您還需要在componentDidMount
具有類似的邏輯,以防萬一安裝過程中確實具有令牌值。 否則它將無法進行初始呼叫。
作為一個鈎子,這是所有需要的代碼:
useEffect(() => {
makeApiCall(props.token)
}, [props.token])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.