如果没有事件,React组件就不会渲染



我正在学习React,并且正在与API.AI代理创建聊天机器人的个人项目。我正在我的项目中使用API.AI NPM软件包,用户可以提出问题,而我的代理商将根据问题回答答案。该页面直到有关键事件。

以下是我的代码

    import React, {
Component
} from 'react';
import ChatMessageComposer from 
'../ChatMessageComposer/ChatMessageComposer';
 import ChatHistory from '../ChatSection/ChatHistory/ChatHistory';
 import apiai from 'apiai-promise';
class Chat extends Component {
state = {
    messages: [], //[{from: 'bot', message: 'Hi'}]
    inputValue: ''
}
atKeyPress = (event) => {
    if (event.key !== 'Enter') {
        return;
    }
    this.setState((prevState) => {
        prevState.messages.push({
            message: this.state.inputValue,
            from: 'you'
        })
    })
    let data = this.state.inputValue;
    var app = apiai("");
    app.textRequest(data, {
        sessionId: ''
    }).then((response) => {
        console.log(response);
        this.setState((prevState) => {
            prevState.messages.push({
                message: response.result.fulfillment.speech,
                from: 'bot'
            })
        })
    }).catch((error) => {
        console.log(error);
    })

    this.setState({
        inputValue: ''
    });
}
render() {
    console.log("here ", this.state.messages)
    return (<
        div >
        <
        ChatHistory messages={
                this.state.messages
            } > < /ChatHistory> <
        ChatMessageComposer 
                changed={
                    (event) => this.setState({
                        inputValue: event.target.value
                    })
                }
                atKeyPress={
                    (event) => this.atKeyPress(event)
                }
                value={
                    this.state.inputValue
                }
            >
                < /ChatMessageComposer> <
        /div>
    )
}

}

    export default Chat;

这是Chatmessagecomposer组件,

    export default Chat;
    const chatMessageComposer = (props) => {
    return (
    <div className={classes.Chatinput}>
    <input placeholder="Talk to me..." className={classes.Userinput}                 type="text" value={props.value} onChange={props.changed} onKeyPress=        {props.atKeyPress}/>
    </div>
    )
    }
   const chatHistory = (props) => (
   <div className={classes.ChatOutput}>
   {props.messages.map((message, i)=>(
   <ChatMessage key={i} message={message} />
  ))}
  </div

任何帮助将不胜感激

您没有在setState方法调用中返回突变状态。尝试这样做

this.setState((prevState) => {
        prevState.messages.push({
            message: response.result.fulfillment.speech,
            from: 'bot'
        })
        return prevState; 
    })

相关内容

  • 没有找到相关文章

最新更新