React Component
目录
- React 组件细节
- componentDidMount只执行一次(最后更新:2021-03-18 14:48)
componentDidMount 只执行一次
//parent.jsx
class Parent extends Component{
state = {
list:[{
id:1
},{
id:2
}]
}
render(){
const {list} = this.state;
return <div>
{list.map((item,index)=>{
return (<div key={index}>
//这里的key 作用是将遍历组件做唯一区分,这样组件的Component生命周期才可以顺序执行。否则将当做一个组件,导致参数`id`变化,而组件的componentDidMount只执行一次
查看<Child id={item.id} key={item.id}></Child>
</div>)
})}
</div>
}
}
//child.jsx
class Child extends Component {
constructor(props) {
super();
this.state = {
id: props.id, //由父组件传递
};
}
componentDidMount() {
console.log(this.state.id);//>根据父组件中的参数`key`变化是则会再次执行
}
render(){
return(
<span>{this.state.id}</span>
)
}
}