[英]React component not rendering without an event
我正在學習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;
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.