簡體   English   中英

TypeError:無法將子組件中未定義的屬性“setState”讀取到父組件

[英]TypeError: Cannot read property 'setState' of undefined in child to parent component

我收到以下錯誤。

TypeError: Cannot read property 'setState' of undefined
closeAlert

這似乎是綁定或道具問題?

所以我該怎么做?

主要成分:

class App extends React.Component {
constructor(props) {
    super(props);

    this.state = {
        alertOpen : false
    };

    this.closeAlert.bind(this);
}

closeAlert(event) {
    this.setState({
        closeAlert : true
    });
}

render() {
    return (
        <div>
            <AlertWindow
closeAlert={this.closeAlert}
             />
        </div>
    );
}
}

子組件:

    const AlertWindow = ({ closeAlert }) => {
    return (
    <Alert type="primary">

    <Button
      color="secondary"
      RootComponent="button"
      onClick={(event) => {
        closeAlert(event)
      }}
    >
      No, thanks
    </Button>
  </Button.List>
   </Alert>
  );
  };

您的綁定語句不正確,將其更改為以下內容:

this.closeAlert = this.closeAlert.bind(this);

您需要將綁定的 function 分配給 class 方法。 沒有賦值綁定是不夠的。

希望這會有所幫助!

另一個簡單的解決方法:將您的 cloaseAlert 方法轉換為:

closeAlert=(event)=> {
  this.setState({
    closeAlert : true
  });
}

現在您不需要構造函數中方法的綁定語句

我想你對命名有點困惑。 您正在設置alertOpen state。 不太確定AlertWindow做了什么,但您需要一個調用 closeAction 的操作(如onClick={this.closeAlert}

同樣正如@Alexander 提到的,您的綁定不正確。

class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            alertOpen : true
        };

        this.closeAlert = this.closeAlert.bind(this);
    }

    closeAlert(event) {
        this.setState({
            alertOpen : false
        });
    }

    render() {
        return (
            <AlertWindow
closeAlert={this.state.closeAlert}
             />
        );
    }
}

您的“打開”和“關閉”混淆了,所以我不知道最初的 state 應該是什么。

暫無
暫無

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

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