猿问

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

我有 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>


慕娘9325324
浏览 172回答 3
3回答

江户川乱折腾

删除组件DidUpdate(),因为刷新数据不依赖于属性来获取数据,并且没有对 prevProps 和 newProps 进行任何检查。您可以从“添加”或“保存按钮”回调中调用刷新数据方法。我想象你正在保存模态代码中的数据,添加 setState 回调。模式保存数据,隐藏设置显示状态为 false,并从一次调用刷新数据。let addModalClose = () => this.setState({addModalShow:false}, this.refreshData)

绝地无双

您正在调用执行某些操作,然后设置状态。设置状态后,调用函数,然后再次调用,设置无限循环。要使其正常工作,请从上一个进行比较,然后根据需要调用。this.refreshList();rendercomponentDidUpdatepropsthis.refreshList();componentDidUpdate(prevProps) {&nbsp; // Typical usage (don't forget to compare props):&nbsp; if (this.props.depid !== prevProps.depid) { //Replace `depid` with the props you like to compare changes. If that is changed, then only call&nbsp; &nbsp; this.refreshList();&nbsp; }}您可以在组件DidUpdate()中立即调用 setState(),但请注意,它必须包装在类似上例的条件下,否则将导致无限循环。它还会导致额外的重新渲染,虽然对用户不可见,但会影响组件性能。如果你试图将某种状态“镜像”到来自上面的道具,请考虑直接使用道具。阅读更多关于为什么将道具复制到状态会导致错误的信息。查看文档: https://reactjs.org/docs/react-component.html#componentdidupdate

MMTTMM

问题是您正在调用组件加载和组件冗余更新。如文档中所述:https://reactjs.org/docs/react-component.html#componentdidupdaterefreshList您应该在某种条件下避免组件中的无限循环Did更新。
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答