Javascript 设置不使用开关块的状态

Javascript 设置不使用开关块的状态,javascript,reactjs,bots,setstate,Javascript,Reactjs,Bots,Setstate,我正在尝试构建一个小型聊天机器人,如果不是因为这个bug,我似乎即将完成。问题似乎是我的switch语句没有正确处理setState Uquestion extends React.Component { constructor(props) { super(props); this.state = { text: this.props.text, response: "Here is the answer" } this.hand

我正在尝试构建一个小型聊天机器人,如果不是因为这个bug,我似乎即将完成。问题似乎是我的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"))
uq扩展了React.Component{
建造师(道具){
超级(道具);
此.state={
text:this.props.text,
回答:“这是答案”
}
this.handleChange=this.handleChange.bind(this)
this.key=this.key.bind(this)
this.fetchResponse=this.fetchResponse.bind(this)
}
手变(活动){
这是我的国家({
问题:event.target.value
})
}
fetchResponse(){
开关(this.state.searchKey){
“烧烤”个案:
这是我的国家({
回应:“德克萨斯烧烤”
})
打破
案例“书”:
这是我的国家({
回答:“很接近,但可能是托比亚斯·沃尔夫所说的那个晚上。”
})
打破
案例“餐厅”:
这是我的国家({
回答:“安达曼,德克萨斯州丹顿的一个泰国小景点。”
})
打破
案例“工作”:
这是我的国家({
回答:“很多这个,很多那个。”
})
打破
“教养”一案:
这是我的国家({
回应:“德克萨斯州雷雨横扫无边的平原。”
})
打破
案例“未来”:
这是我的国家({
回应:“我希望能从事有意义的应用,并写出有意义的叙述”
})
打破
案例“乐趣”:
这是我的国家({
回答:“月圆时,我用烛光写字。”
})
打破
违约:
这是我的国家({
回答:“嗯,什么?”
})
}
}
//此函数设置一个键,我稍后将使用该键获取对用户问题的响应。
键(){
var-question=this.state.question;
var questionUpper=question.toUpperCase();
//is not-1确定短语是否出现在问题的任何地方。
如果(问题上限搜索(“最喜欢的食物”)!=-1){
这是我的国家({
搜索键:“烧烤”
},this.fetchResponse())
} 
else if(questionUpper.search(“最喜欢的书”)!=-1){
这是我的国家({
搜索键:“书”
},this.fetchResponse())
} 
else if(questionUpper.search(“FAVORITE RESTAURANT”)!==-1{
这是我的国家({
搜索键:“餐厅”
},this.fetchResponse())
} 
else if(questionUpper.search(“工作经历”)!=-1){
这是我的国家({
搜索键:“工作”
},this.fetchResponse())
} 
否则(问题Upper.search(“成长”)!=-1){
这是我的国家({
搜索键:“养育”
},this.fetchResponse())
} 
else if(questionUpper.search(“最喜爱的作者”)!=-1){
这是我的国家({
搜索键:“作者”
},this.fetchResponse())
} 
else if(questionUpper.search(“FUTURE”)!=-1){
这是我的国家({
搜索键:“未来”
},this.fetchResponse())
} 
else if(questionUpper.search(“寻找乐趣”)!=-1){
这是我的国家({
搜索键:“乐趣”
},this.fetchResponse())
}
否则{
这是我的国家({
搜索键:“默认”
},this.fetchResponse())
}
} 
render(){
返回(
{this.state.response}

{this.props.text} 问! ); } } ReactDOM.render(,document.getElementById(“内容”))
您在
setState
函数中传递了错误的回调。在
fetchResponse
中,您编写了一些错误的案例。我已经纠正了您的错误,您可以在中的工作示例中看到

错误:

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

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

您可以阅读源代码

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)

你说的“不正确处理设置状态”是什么意思?出什么问题了?嘿,本,当我问“你最喜欢的食物是什么?”时,用户界面中的回答会变成默认值。然后,如果我再次单击“询问”按钮,响应将在UI中正确更新。但是,在此之后,“询问”按钮不会提示任何更改。我相信这是setState的一个问题,特别是当它出现在开关块中时。不过我真的不确定。我是个初学者。这是代码笔:我只有一个问题:你为什么要在UI库中编写聊天机器人?React是我唯一掌握的框架。还有什么更好的选择呢?当,这有点尴尬,因为那些不匹配的案例!感谢您提供此解决方案。这是关于我反应能力的程度。你建议后续项目吗?非常感谢你!欢迎你)点击接受我的答案,如果它解决了你的问题)如果你还有其他问题-我会一直很乐意帮助你,这看起来很难理解lol,但是这是setState的实际流程吗?是的!这就是react use setState发生的情况。也许我应该多加些代码。我认为react的源代码在某些情况下并不是不可理解的,只是因为我现在有点累了,只是太懒了:D