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

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

React:無法在尚未安裝的組件上調用 setState

React:無法在尚未安裝的組件上調用 setState

倚天杖 2023-04-27 17:03:44
我正在使用 react(MERN stack) 創建一個簡單的待辦事項應用程序。當我嘗試同時使用 axios 和 setState 調用 get API 時出現上述警告。我已經通過堆棧溢出的其他線程解決了同樣的問題,但沒有一個真正有用。我什至試過弄亂“isMounted”變量。下面是我的代碼...export default class App extends React.Component{  _isMounted = false;  constructor(props){    super(props);    this.state = {list:[], itemCounter: 0};    this.addItem = this.addItem.bind(this);    this.handleDone = this.handleDone.bind(this);    this.componentDidMount = this.componentDidMount(this);  }    componentDidMount(){    this._isMounted = true;    axios.get(`http://localhost:8000/todo/api/`)      .then(res => {        if(this._isMounted){          const list = res.data;          const unDoneList = list.filter(task => task.done === false)          this.setState({ list: list, itemCounter: unDoneList.length });      }});  }  componentWillUnmount() {    this._isMounted = false;  }  addItem(val) {    axios.post('http://localhost:8000/todo/api/task/', { data: val })    .then(res => {      const itemCounter = this.state.counter + 1;      const updatedList = this.state.list;      updatedList.push({ data: val, done: false });      console.log(res);      console.log(res.data);      this.setState({ list: updatedList, itemCounter: itemCounter });    })  }    handleDone(item){    console.log(item._id)    axios.post(`http://localhost:8000/todo/api/delete/${item._id}`)    .then(() => console.log("Item Deleted."));    let updatedList = this.state.list;    updatedList.forEach(task => {      if(task.id === item.id ){        task.done = true;      }    });        const itemCounter = this.state.itemCounter - 1;    this.setState({ list: updatedList, itemCounter: itemCounter });  }作為參考,我已經在 GitHub 上上傳了我的整個項目: https: //github.com/mohnishm/Todo-App-in-React 如何擺脫這個警告?
查看完整描述

2 回答

?
猛跑小豬

TA貢獻1858條經驗 獲得超8個贊

componentDidMount您正在構造函數中調用生命周期方法,您不應該那樣做。

這是問題所在:

this.componentDidMount = this.componentDidMount(this);

如果您在 中執行此操作constructor,您會收到該警告,React 會告訴您該組件尚未安裝,但您已經setState通過手動調用componentDidMount.

在您的情況下,構造函數尚未完成執行,并且組件沒有機會安裝到 DOM 上。一旦構造函數被執行,組件就被初始化,然后組件被實際掛載到 DOM 上。

安裝組件后,你的生命周期方法componentDidMount將由 React 以適當的上下文調用(因此不需要調用bindon componentDidMount),然后在那個時間點你應該調用setState來改變組件的狀態。

您也可以刪除_isMounted與該財產形式相關的 和檢查componentDidMount,componentWillUnmount因為它不是必需的。


查看完整回答
反對 回復 2023-04-27
?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

componentDidMount 是一種生命周期方法,不需要在構造函數中進行初始化。刪除它以避免警告。


  constructor(props){

    super(props);

    this.state = {list:[], itemCounter: 0};

    this.addItem = this.addItem.bind(this);

    this.handleDone = this.handleDone.bind(this);

    this.componentDidMount = this.componentDidMount(this); // remove this, componentDidMount is a lifecycle method.

  }


查看完整回答
反對 回復 2023-04-27
  • 2 回答
  • 0 關注
  • 155 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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