[英]React component renders 1 turn latter
我是 React 新手,我不知道如何稱呼我面臨的問題
我有一個朋友列表,當列表為空時,會顯示一條消息,指示“添加要在此處顯示的朋友”
當我添加朋友時,消息應該消失
問題是我需要使用生命周期方法來完成它,例如 componentDidUpdate()。
功能是存在的,但正如標題所示,我稍后稱之為 1 轉或移動
我會解釋:
我看到添加朋友的消息,但是當我單擊添加朋友時,它不會消失,直到我添加第二個朋友。 當我刪除所有朋友時,該消息不會再次出現,但是當我添加新朋友時,所以輪到后者,我做一件事,然后在下一個動作中重新渲染組件
我確定它很簡單,但是我已經為此苦苦掙扎了兩天,但我找不到如何讓它立即工作。
這是代碼
import React, { Component } from 'react';
import Title from './title';
/* I'm using this var, because when I try to set it with a state I get an infinite loop */
var title = "Add friends to view them here";
class FriendList extends Component {
constructor(props){
super(props)
}
componentWillReceiveProps(nextProps){
/* friendList is an array with friends objects */
if(this.props.friendList.length > 0){
console.log("this is "+ title);
title = "";
}else{
title = "Add friends to view them here";
console.log("this is "+ title);
}
}
render(){
let friends = this.props.friendList;
return(
<div className="friend-list">
<p>{title}</p>
<div>
{Object.keys(friends).map((key) => {
var friend = friends[key];
return (
<div className="friendData">
<img className="friendPhoto"src={friend.profilePic} alt={friend.profilePic}/>
<div className="friend">
{friend.name}
<br/>
{friend.city}
</div>
<button className="delete" onClick={() => this.props.deleteFriend(friend)} >X</button>
</div>
);
}
)}
</div>
</div>)
}
}
export default FriendList;
請包含 Browser React Debugger 擴展的屏幕截圖,其中包含所有變量 state,props 擴展。
可能是您的組件沒有重新渲染。 我以前也遇到過這種問題。
另外,您能否嘗試關閉開發人員工具(F12)。 只有在我的開發工具打開的情況下,我的應用程序才會執行 1 次滴答之前,我遇到了一個問題。 我的元素應該只在我懸停時改變顏色,當我懸停時恢復到原始顏色,但是當我的開發工具打開時,即使我已經懸停,它也會停留在改變的顏色上。
您可以有條件地呈現標題
<p>{this.props.friendList.length === 0 ? title : null}</p>
代替
<p>{title}</p>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.