【问题标题】:setState not working with Switch blocksetState 不适用于 Switch 块
【发布时间】:2016-11-25 20:48:32
【问题描述】:

我正在尝试构建一个小型聊天机器人,如果不是因为这个错误,我似乎已经接近完成。问题似乎是我的 switch 语句没有正确处理 setState 。

Uquestion extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      text: this.props.text, 
      response: "Here is the answer"
    }

    this.handleChange = this.handleChange.bind(this)

    this.key = this.key.bind(this)

    this.fetchResponse = this.fetchResponse.bind(this)
  }


  handleChange(event) {
    this.setState({
      question: event.target.value
    })
  }

  fetchResponse() {
    switch(this.state.searchKey) {
      case "BBQ": 
        this.setState({
          response:"Texas BBQ" 
        })
      break; 
      case "book": 
        this.setState({
          response:"It's close, but probably The Night in Question by Tobias Wolff." 
        })
      break;
      case "restaurant": 
        this.setState({
          response:"Andaman, a little Thai spot in Denton, Texas." 
        })
      break;
      case "work": 
        this.setState({
          response:"Lots of this and lots of that." 
        })
      break;
      case "upbringing": 
        this.setState({
          response:"Texas thunderstorms over endless plains." 
        })
      break;
      case "future": 
        this.setState({
          response:"I hope to work on meaningful applications and write meaningful narratives" 
        })
      break;
      case "fun": 
        this.setState({
          response:"When the moon is full, I write by candle light." 
        })
      break;
      default: 
        this.setState({
          response:"Um, what?" 
        })
    }
  }

  //this function sets a key that I will later use to fetch a response to the user's question.
  key() {
    var question=this.state.question; 
    var questionUpper=question.toUpperCase();  

    // the is not -1 determines if the phrase appears anywhere in the question.
    if(questionUpper.search("FAVORITE FOOD")!==-1) {
      this.setState({
        searchKey:"BBQ" 
      }, this.fetchResponse())
    } 
    else if(questionUpper.search("FAVORITE BOOK")!==-1) {
      this.setState({
        searchKey:"Book" 
      }, this.fetchResponse())
    } 
    else if(questionUpper.search("FAVORITE RESTAURANT")!==-1) {  
      this.setState({
        searchKey:"Restaurant" 
      },this.fetchResponse())
    } 
    else if(questionUpper.search("WORK EXPERIENCE")!==-1) {
      this.setState({
        searchKey:"work" 
      },this.fetchResponse())
    } 
    else if(questionUpper.search("GROWING UP")!==-1) {
      this.setState({
        searchKey:"upbringing" 
      },this.fetchResponse())
    } 
    else if(questionUpper.search("FAVORITE AUTHOR")!==-1) {
      this.setState({
        searchKey:"author" 
      },this.fetchResponse())
    } 
    else if(questionUpper.search("FUTURE")!==-1) {
      this.setState({
        searchKey:"future" 
      },this.fetchResponse())
    } 
    else if (questionUpper.search("FOR FUN")!==-1) {
      this.setState({
        searchKey:"fun" 
      },this.fetchResponse())
    }
    else {
      this.setState({
        searchKey:"default" 
      }, this.fetchResponse())
    }
  } 

  render() {
    return (
      <div> 
        <p> {this.state.response} </p> 
        <textarea onChange = {this.handleChange} className="q">       {this.props.text} </textarea> 
        <button className="a" onClick={this.key}>Ask!</button> 
      </div>
    );
  }
}
ReactDOM.render(<Uquestion text="Type Question Here."/>,      document.getElementById("content"))

【问题讨论】:

  • “没有正确处理 setState”是什么意思?出了什么问题?
  • 嘿,Ben,所以当我问“你最喜欢的食物是什么?”响应更改为 UI 中的默认值。然后,如果我再次单击询问按钮,响应会在 UI 中正确更新。但是,在此之后,询问按钮提示没有更改。我相信这是 setState 的一个问题,尤其是当它出现在 switch 块中时。不过我真的不确定。我是初学者。
  • 这里是密码笔:codepen.io/WriterState/pen/xOAApB
  • 我只有一个问题:为什么要在 UI 库中编写聊天机器人?
  • React 是我唯一掌握的框架。有什么更好的选择?

标签: javascript reactjs bots setstate


【解决方案1】:

你可以阅读反应源代码

ReactComponent.prototype.setState = function (partialState, callback){
  !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state  variables to update or a function which returns an object of state variables.') : _prodInvariant('85') : void 0;
  this.updater.enqueueSetState(this, partialState);
  if (callback) {
    this.updater.enqueueCallback(this, callback, 'setState');
  }
};

enqueueCallback: function (publicInstance, callback, callerName) {
  ReactUpdateQueue.validateCallback(callback, callerName);
  var internalInstance = getInternalInstanceReadyForUpdate(publicInstance);

  if (!internalInstance) {
    return null;
  }

  if (internalInstance._pendingCallbacks) {
    internalInstance._pendingCallbacks.push(callback);
  } else {
    internalInstance._pendingCallbacks = [callback];
  }

  enqueueUpdate(internalInstance);
}

function enqueueUpdate(internalInstance) {
  ReactUpdates.enqueueUpdate(internalInstance);
}

所以,我认为你的回调是这样的:

this.setState({
  searchKey:"BBQ" 
}, this.fetchResponse)

【讨论】:

  • 这看起来非常难以理解,哈哈,但这是 setState 发生的实际流程吗?
  • 是的!这就是 react 使用 setState 发生的情况。也许我应该放更多的代码。我认为 React 源代码在某些情况下并非不可理解。
  • 只是无法理解,因为我现在有点累,只是超级懒惰:D
【解决方案2】:

您在 setState 函数中传递了错误的回调。在fetchResponse 你写了一些错误的案例。我已经纠正了您的错误,您可以在 Codepen 中查看工作示例

错误:

this.setState({
  searchKey: "book"
}, this.fetchResponse())

正确:

this.setState({
  searchKey: "book"
}, this.fetchResponse)

【讨论】:

  • 该死,这有点尴尬,那些不匹配的案例怎么办!感谢您提供此解决方案。这是关于我的 React 能力的程度。你建议一个后续项目吗?非常感谢!
  • 不客气)如果它解决了您的问题,请单击以接受我的回答)如果您还有其他问题 - 我将永远乐意提供帮助
猜你喜欢
  • 2021-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 2019-08-29
  • 1970-01-01
相关资源
最近更新 更多