亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

組件后的無限循環 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 關注
  • 197 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號