簡體   English   中英

SetState不是OnChange上的函數

[英]SetState Is Not A Function on OnChange

正在努力獲得一個滑塊,以在React狀態下更改“文本”的值。

不斷出現錯誤:

盡管我盡了最大的故障排除努力,但“ App.js:90 Uncaught TypeError:this.setState不是一個函數”。

解決辦法是什么?

  class App extends Component {
  constructor(props) {
      super(props);
      this.state = {list: [{x: "Before Pool", y:85000}, {x: "After Pool", y:82000}], text: 0, options: {bathrooms:'', bedrooms:'', sqft:''}};
    }

  componentDidMount() {
        setTimeout(() => {
         this.setState({list: [{x: "Before Pool", y:60000}, {x: "After Pool", y:30000}]});
         console.log("testing", this.state.text);
       }, 2000) ;
  }
  handleChange (event) {
    console.log("from handle change", event);
   this.setState({text : event });
  }
  render() {
    return (
      <div className="App">
          <div>
             <div style={wrapperStyle}>
               <p># of Bathrooms</p>
               <Slider min={0} max={20} defaultValue={3} onChange={this.handleChange} />
             </div>

在此處輸入圖片說明 在此處輸入圖片說明

您需要綁定handleChange方法

<Slider min={0} max={20} defaultValue={3} onChange={this.handleChange.bind(this)}

由於您處於不同的上下文中,因此需要將狀態綁定到setTimeout的回調。 我相信這可以解決問題:

setTimeout(() => {
 this.setState({list: [{x: "Before Pool", y:60000}, {x: "After Pool", y:30000}]});
 console.log("testing", this.state.text);
   }.bind(this), 2000) ;

答案很簡單:您在看錯this

由於您是在閉包中編寫回調,因此重要的是要知道您不能從外部訪問this 它總是指當前上下文。

解決方法是定義您自己的變量(通常稱為self )以在閉包內部使用:

componentDidMount() {
    var self = this; // copy the reference
    setTimeout(() => {
        self.setState({list: [{x: "Before Pool", y:60000}, {x: "After Pool", y:30000}]});
        console.log("testing", this.state.text);
    }, 2000) ;
}

您需要在此處綁定handleChange方法

<Slider min={0} max={20} defaultValue={3} onChange={this.handleChange} />

看起來應該像這樣

<Slider min={0} max={20} defaultValue={3} onChange={this.handleChange.bind(this)} />

或者,您可以在方法的簽名中簡單地使用“箭頭函數”,最好一直使用此功能來節省您一直綁定的時間。 它看起來應該像這樣:

handleChange = event => {
    console.log("from handle change", event);
    this.setState({text : event });
  }

暫無
暫無

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

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