我有一组 id。我想运行一个循环遍历 id 数组的 map 函数。每次循环到一个新的 id 元素时,我想使用该 id 来触发一个返回对象的函数。然后我想使用该对象的值来返回内容。这是我的代码:
...
getConversationInfo = async (conversation_id, listing_type, listing_id, user_id, sender_id, respondent_id) => {
let conversation = await axios.get(`${propState.host}/api/conversation/${listing_type}/${listing_id}/${user_id}/${sender_id}/${respondent_id}`);
conversation = conversation.data;
console.log("conversation: ", conversation);
let listing = await conversation.listing;
let person_you_are_messaging = await conversation.person_you_are_messaging;
let listing_name;
if(listing.business_name) {
listing_name = await listing.business_name;
} else {
listing_name = await listing.short_description;
}
let conversationObj =
{
listing_name: listing_name,
person_you_are_messaging: person_you_are_messaging.first_name + " " + person_you_are_messaging.last_name
};
console.log("conversationObj: ", conversationObj);
return conversationObj;
}
...
render() {
const { user_id, conversations, showNoConversationsMessage, showShowMoreButton, loading } = this.state;
return (
...
<ScrollView>
<View style={styles.body}>
{conversations.map(async (e, i) => {
let conversationObj = await this.getConversationInfo(e.conversation_id, e.listing_type, e.listing_id, user_id, e.sender_id, e.respondent_id);
console.log("in map conversation: ", conversationObj, conversationObj.listing_name, conversationObj.person_you_are_messaging);
return (
<TouchableOpacity
key={i}
style={styles.conversation}
onPress={() => {
this.props.updateSingleState("conversation_id", e.conversation_id);
this.props.updateState("Conversation");
}}
>
<Text style={styles.text}>Listing Name: {conversationObj.listing_name}</Text>
<Text style={styles.text}>Sender or Respondent Name: {conversationObj.person_you_are_messaging}</Text>
</TouchableOpacity>
)
}
)}
</View>
</ScrollView>
...
我在 map 函数中的 console.log 返回了我想要的值。但我总是收到这个错误:
“对象作为 React 子对象无效(找到:带有键 {_40、_65、_55、_72} 的对象。如果您打算渲染子对象集合,请改用数组。”
如何使错误消息消失?
答案 0 :(得分:0)
在 {conversations.map(async (e, i) => {
中,对话不是数组。
确保您将 'conversationObj' 作为数组返回。
使用'try catch'方法并在返回之前对conversationObj进行一些验证
答案 1 :(得分:0)
我没有在 map 函数内部运行 getConversationInfo 函数,而是在 componentDidMount 内部运行它,并将该信息与 this.state.conversations 信息结合起来,一切都奏效了。
我认为最大的教训是永远不要更新地图函数中渲染方法内部的信息。最好先更新 componentDidMount 中的状态,然后将该信息用于您使用的任何地图函数。