【问题标题】:SetState Is Not A Function on OnChangeSetState 不是 OnChange 上的函数
【发布时间】:2017-01-04 10:17:49
【问题描述】:

正在努力获得一个滑块来更改 React 状态下“文本”的值。

不断报错:

“App.js:90 Uncaught TypeError: this.setState is not a function”尽管我尽了最大的努力排除故障。

解决办法是什么?

  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>

【问题讨论】:

    标签: javascript reactjs state onchange setstate


    【解决方案1】:

    你需要绑定handleChange方法

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

    【讨论】:

    • 能否将我的答案标记为正确答案,以便其他人得到帮助
    【解决方案2】:

    您需要将您的状态绑定到setTimeout 中的回调,因为您处于不同的上下文中。 我相信这会成功:

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

    【讨论】:

    • 很高兴听到这个消息,如果您的问题得到完全解决,那么您可以接受一个向其他用户表明这一点的答案。当然,它不需要是我的,但如果你接受它会很有帮助。
    【解决方案3】:

    答案很简单:你看错了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) ;
    }
    

    【讨论】:

    • 欣赏它@Mario!您的答案与其他两个答案相呼应 - 很好的分析。
    【解决方案4】:

    这里需要绑定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 });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-28
      相关资源
      最近更新 更多