【问题标题】:React reuses components instead of creating new so that I have to rely on componentWillReceiveProps to load fresh dataReact 重用组件而不是创建新组件,因此我必须依靠 componentWillReceiveProps 来加载新数据
【发布时间】:2021-08-21 18:25:20
【问题描述】:

我对 ReactJS 有一个问题,因为当在父组件的状态下存储子组件(作为缩略图)时,存储为组件数组的子组件被构造一次并且 c​​omponentDidMount 被调用一次。一旦我“重新导入”数据并根据来自后端 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


    【解决方案1】:

    你可以使用 componentDidUpdate() 并且可以从官方网站查看文档。

    componentWillReceiveProps 已过时,不推荐使用。一个更好的主意是将来自后端的数据存储在某些上下文/redux 中。这将导致子组件使用更新的数据重新渲染。

    【讨论】:

      猜你喜欢
      • 2014-08-16
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 2023-03-22
      • 2021-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多