簡體   English   中英

在使用ES2016的React中的箭頭功能中調用setState時未安裝組件

[英]Component not mounted when setState called in arrow function in React with ES2016

注意: 我重新構建了我的問題,使其更容易理解。 但是,我保留舊版本用於歷史目的。

我有一個React應用程序,當我從一個箭頭函數調用this.setState() ,我得到“組件未掛載消息”。 這是我的組件:

import React, { Component } from 'react'

class Test extends Component {
    state = {
        value: ''
    }

    onChange = (e) => {
        e.preventDefault()
        this.setState({
            value: e.target.value
        })
    }

    render() {
        return <input value={ this.state.value } onChange={ this.onChange } />
    }
}

當我輸入輸入時,我收到以下錯誤消息:

Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op.

我不知道為什么會這樣,因為箭頭函數不應該被分箱,並且因為這是通過鍵入觸發的,所以組件顯然是被掛載的。

謝謝你的幫助!


這是此問題的先前版本:

我有一個非常標准的React應用程序,當我從一個箭頭函數調用this.setState() ,我得到“組件未掛載消息”。

代碼看起來像這樣:

 onClick = () => { this.setState({clicked: true}) } ... render() { return <AnotherComponent onClick={ this.onClick } /> } 

當調用onClick ,我收到以下消息:

 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. 

我不確定是什么導致這種情況,因為我使用箭頭功能,但它仍然無法正常工作。

編輯:如所問,這是AnotherComponent

 const AnotherComponent = (props) => { return ( <div> <Button primary>Reject</Button> <Button primary onClick={ props.onClick }>Edit Post</Button> <Button primary>Approve</Button> </div> ) } 

謝謝

當你說onClick={ this.onClick }你會說“這是一個可以使用的功能”。 然而,它失去了它的背景。

bind() onClick()傳遞給屬性之前,需要bind() onClick() bind()的上下文。 最好的地方是在你班級的constructor中。

class MyClass extends React.Component {
     constructor(props) {
       super(props); // have to do this part in any Component constructor
       this.onClick = this.onClick.bind(this);
     }

     onClick() {
       this.setState({ clicked: true });
     }

     render() {
       return <AnotherComponent onClick={ onClick } />;
     }
}

或者,如果您的函數很短,您可以在構造函數中創建它:

constructor(props) {
  super(props);

  this.onClick = () => { this.setState({ clicked: true }); };
}

通過在構造函數的上下文中創建,它將被隱式綁定。

你的組件是完全正確的,現在我們只需要知道你在哪里調用它。

此問題通常來自父級,只需檢查父級是否已完全裝入。

事實上:

  • onChange不需要e.preventDefault()
  • 每當你輸入輸入時,它會調用設置state
  • 每次state設定,
  • 它再次觸發生命周期方法render() (它重新加載節點),因此在這種情況下。
  • 當你preventDefault() ,你打破了生命周期組件的常規流程:)刪除它,警告將消失。

====================第2部分===========================

哦,我現在看,一切都很清楚:D

Whenever you call the onClick = () => {
    this.setState({clicked: true})
}

...

render() {
    return <AnotherComponent onClick={ this.onClick } />
}

你想通過props傳遞函數,但是你將它設置為onClick事件,它是一個保留字

你應該通過一個保留的道具傳遞它,如:

return <AnotherComponent handleClick={ this.onClick } />

然后對孩子:

<Button primary onClick={ props.handleClick }>Edit Post</Button>

現在你創建了一個實際的屬性

希望它能幫助你:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM