[英]How to re-render a component when it changes its props async?
我在一個項目中使用React和Redux我有兩個組件,父母和孩子。
當子組件接收到它所調用的某些動作時,父組件將一些道具傳遞給子項,這些動作會更改父項傳遞給其子項的一些道具(異步)。 現在我的redux-store顯示數據已成功存儲在其中。 但我的子組件不會重新渲染自己。
父組件:
class Parent extends React.Component {
getChilds(){
let child = [];
let i = 0;
for (let keys in this.props.home.data) {
child[i] = (
<Child title={keys} data={this.props.home.data[keys]} key={keys} />
);
i++;
if (i === 6) break;
}
return Rows;
}
render(){
return (
<div>
<h1>I am gonna call my child </h1>
{this.getChilds()}
</div>)
}
}
子組件:
class Child extends React.Component {
// Here I'm not sure which lifecycle method to use to i'm gonna use
// componentDidMount
componentDidMount(){
if(this.props.data.items.length === 0){
// calling an action to fill this.props.data.items array with data
this.props.getData(this.props.data.id);
}
}
getGrandSong(){
let grandSons = [];
if(this.props.data.items.length > 0){
grandSons = this.props.data.items.map( item => <GrandSon item={item}
/>);
}
return grandSons;
}
render(){
return (
<div>
<h1> I am the child component and I will call my own child </h1>
{this.getGrandSon()}
</div>
)
}
當我檢查react-dev工具中的道具時,道具會更新。
每當prop更改時,您都需要重新呈現數據,因此您可以在render函數上調用它,並實現shouldComponentUpdate()
以深入比較props並調用render()
。
所以,在這種情況下:
class Child extends React.Component {
componentDidMount(){
if(this.props.data.items.length === 0){
// calling an action to fill this.props.data.items array with data
this.props.getData(this.props.data.id);
}
}
shouldComponentUpdate(nextProps){
if(this.props.data.items.length === nextProps.data.items.length){
for(let i=0; i< nextProps.data.items ; i ++){
if(nextProps.data.items[i] !== this.props.data.items[i]) return true;
}
}
return true;
}
render(){
const getGrandSong = () => {
let grandSons = [];
if(this.props.data.items.length > 0){
grandSons = this.props.data.items.map( item => <GrandSon item={item} />);
}
return grandSons;
}
return (
<div>
<h1> I am the child component and I will call my own child </h1>
{getGrandSon()}
</div>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.