【发布时间】:2021-08-21 18:25:20
【问题描述】:
我对 ReactJS 有一个问题,因为当在父组件的状态下存储子组件(作为缩略图)时,存储为组件数组的子组件被构造一次并且 componentDidMount 被调用一次。一旦我“重新导入”数据并根据来自后端 API 的新数据创建新的子组件(例如在激活新的排序模式时),组件不会调用 componentDidMount,我必须依靠 componentWillReceiveProps 方法来导入例如图片链接显示在缩略图上(似乎反应重用了组件)。例如,如果子组件中的数据导入缓慢,则会显示旧照片,因为它会记住创建后在自己的 componentDidMount 中完成的先前迭代。
我如何强制做出反应以始终从头开始创建新的子组件,并感谢调用 componentDidMount 以包括从后端导入数据并避免依赖 componentWillReceiveProps 调用?
这是父组件 ComponentManager 从后端导入人员数据并根据检索到的 JSON 创建缩略图的伪代码。然后它可以在用户更改排序顺序后更新缩略图:
class ComponentManager extends Component {
constructor(props) {
super(props);
this.state = {
personsThumbnails : undefined
}
}
componentDidMount() {
// Import person ids and create SinglePersonThumbnail(s) child components as the state personsThumbnails
importPersonsIds();
}
importPersonsIds(sortingMode) {
// Importing persons data from backend API and created thumbnails stored in personsThumbnails state
...
}
render() {
return(
<div>
<button onClick={()=>{this.importPersonsIds("SORT_BY_AGE")}}>Sort by age</button>
<button onClick={()=>{this.importPersonsIds("SORT_BY_NAME)}}>Sort by name</button>
<div>
{this.state.personsThumbnails}
</div>
</div>
);
}
}
class SinglePersonThumbnail extends Component {
constructor(props) {
super(props);
this.state = {
photoUrl : undefined,
personsName : undefined
}
}
componentDidMount() {
// Called when component is created
this.importDataAndPhotoForPerson(this.props.id);
}
componentWillReceiveProps(nextProps) {
// Called always when ComponentManager changes the order of thumbnails upon other sorting mode triggered
this.importDataAndPhotoForPerson(this.props.id);
}
importDataAndPhotoForPerson(id) {
// Imports name of the person and link to photo stored in state
}
render() {
return(
// Display image by link and person's name based on photoUrl and personsName states!
);
}
}
【问题讨论】:
标签: javascript reactjs