我正在尝试使用setState将此对象{ "origin": "user", "message": this.state.message }
添加到messages
数组列表中。现在,我收到以下错误:
Invariant Violation: Objects are not valid as React child (found:object with keys {origin, message})
此外,如果有比setTimeout
更好的方法可以等到消息已呈现,然后再滚动到底部,那也很酷!
sendMessage = () => {
this.setState(prevState => ({
messages: [...prevState.messages, { "origin": "user", "message": this.state.message }]
}));
this.callChatService().then((responseJson) => {
this.setState({
context: responseJson.context
});
for (var i = 0; i < responseJson.output.generic.length; i++) {
this.setState(prevState => ({
messages: [...prevState.messages, { "origin": "bot", "message": responseJson.output.generic[i].text}]
}));
}
})
setTimeout(() => this.refs.flatList.scrollToEnd(), 1500);
this.setState({
message: ""
})
}
renderItem = ({ item }) => {
if (item.origin == "user") {
return (
<View>
<View style={styles.rowRight}>
<Text style={styles.message}>{item}</Text>
</View>
</View>
);
}
else {
return (
<View>
<View style={styles.rowLeft}>
<Text style={styles.message}>{item}</Text>
</View>
</View>
);
}
}
componentWillMount() {
}
render() {
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.title}>{this.state.header}</Text>
</View>
<FlatList
style={styles.list}
ref="flatList"
data={this.state.messages}
keyExtractor={(item, index) => index}
renderItem={this.renderItem}
/>
<KeyboardAvoidingView behavior="padding" keyboardVerticalOffset={20}>
<View style={styles.footer}>
<TextInput
value={this.state.message}
onChangeText={text => this.setState({ message: text })}
style={styles.input}
underlineColorAndroid="transparent"
placeholder="Ask me anything"
/>
<TouchableOpacity onPress={this.sendMessage} style={styles.sendButton} >
<Icon name="send" type="material-icon" size={28} color="#00B2EE" />
</TouchableOpacity>
</View>
</KeyboardAvoidingView>
</View>
);
}
答案 0 :(得分:1)
问题出在您的renderItem
方法的那些行中:
<Text style={styles.message}>{item}</Text>
在这种情况下, item
是一个对象,不能由Text
组件呈现,因此会出错。
考虑到您的代码,我相信它应该像这样item.message
:
<Text style={styles.message}>{item.message}</Text>