为了账号安全,请及时绑定邮箱和手机立即绑定

组件后的无限循环 ReactJS 中的组件更新()

组件后的无限循环 ReactJS 中的组件更新()

慕娘9325324 2022-09-11 20:30:14
我有 React JS 应用程序,它使用来自 ASP .NET Core Web API 的条目更新加速网格表。我需要在插入后使用新条目更新网格。我在那里帮助和使用函数来做到这一点,但我得到了一个函数的无限循环。componentDidUpdate()refreshList()refreshList()关于如何在没有该循环的情况下更新网格的任何想法?import React, {Component} from 'react';import {Table, Container} from 'react-bootstrap';import {Button, ButtonToolbar} from 'react-bootstrap';import {AddDepModal} from './AddDepModal';import {EditDepModal} from './EditDepModal';export class Department extends Component {    constructor(props){        super(props);        this.state = {deps:[], addModalShow: false, editModalShow: false}    }    componentDidMount()    {        this.refreshList();    }    refreshList()    {       fetch("https://localhost:5001/api/departments")       .then(response=> response.json())       .then(data=> {         this.setState({deps:data});       });    }    componentDidUpdate()    {        this.refreshList();    }    render(){     const {deps, depid, depname} = this.state;     let addModalClose = () => this.setState({addModalShow:false})     let editModalClose = () => this.setState({editModalShow:false})    return (        <div>     <Table className = "mt-4" striped bordered hover size ="sm">    <thead>        <tr>            <th>DepartmentID</th>            <th>DepartmentName</th>            <th>Options</th>        </tr>    </thead>
查看完整描述

3 回答

?
江户川乱折腾

TA贡献1851条经验 获得超5个赞

删除组件DidUpdate(),因为刷新数据不依赖于属性来获取数据,并且没有对 prevProps 和 newProps 进行任何检查。

您可以从“添加”或“保存按钮”回调中调用刷新数据方法。

我想象你正在保存模态代码中的数据,添加 setState 回调。

模式保存数据,隐藏设置显示状态为 false,并从一次调用刷新数据。

let addModalClose = () => this.setState({addModalShow:false}, this.refreshData)


查看完整回答
反对 回复 2022-09-11
?
绝地无双

TA贡献1946条经验 获得超4个赞

您正在调用执行某些操作,然后设置状态。设置状态后,调用函数,然后再次调用,设置无限循环。要使其正常工作,请从上一个进行比较,然后根据需要调用。this.refreshList();rendercomponentDidUpdatepropsthis.refreshList();


componentDidUpdate(prevProps) {

  // Typical usage (don't forget to compare props):

  if (this.props.depid !== prevProps.depid) { //Replace `depid` with the props you like to compare changes. If that is changed, then only call

    this.refreshList();

  }

}

您可以在组件DidUpdate()中立即调用 setState(),但请注意,它必须包装在类似上例的条件下,否则将导致无限循环。它还会导致额外的重新渲染,虽然对用户不可见,但会影响组件性能。如果你试图将某种状态“镜像”到来自上面的道具,请考虑直接使用道具。阅读更多关于为什么将道具复制到状态会导致错误的信息。


查看文档: https://reactjs.org/docs/react-component.html#componentdidupdate


查看完整回答
反对 回复 2022-09-11
?
MMTTMM

TA贡献1869条经验 获得超4个赞

问题是您正在调用组件加载和组件冗余更新。如文档中所述:https://reactjs.org/docs/react-component.html#componentdidupdaterefreshList

您应该在某种条件下避免组件中的无限循环Did更新。


查看完整回答
反对 回复 2022-09-11
  • 3 回答
  • 0 关注
  • 171 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号