[英]TypeError: Cannot read property 'map' of undefined in ReactJs?
我正在按照一个反应教程来构建一个聊天应用程序。 但我收到此错误TypeError: Cannot read property 'map' of undefined
in the below code。 我在formattedConversations
function 的第二行收到此错误。 我不知道我在这里做错了什么。 请帮我解决这个问题。
import React, { useContext } from 'react' import useLocalStorage from '../hooks/useLocalStorage' import { useContacts } from './ContactsProvider' const ConversationsContext = React.createContext() export function useConversation() { return useContext(ConversationsContext) } export function ConversationsProvider({ children }) { const [conversations, setConversations] = useLocalStorage('conversations', []) const { contacts } = useContacts() function createConversation(recepients) { setConversations(prevConversations => { return [...prevConversations, { recepients, messages: [] }] }) } const formattedConversations = conversations.map(conversation => { const recepients = conversation.recepients.map(recepient => { const contact = contacts.find(contact => { return contact.id === recepient }) const name = (contact && contact.name) || recepient return { id: recepient, name } }) return {...conversation, recepients } }) const value = { conversations: formattedConversations, createConversation } return ( <ConversationsContext.Provider value={value} > {children} </ConversationsContext.Provider> ) }
此错误表示recepients
未在您的conversation
中设置为数组。
将console.log
放在组件 ex 中。 ConversationsProvider
,
export function ConversationsProvider({ children }) {
... all your code
console.log(conversations)
return ...
}
这样您就可以在任何时候更改此对话以及为什么您的recepients
未正确设置为数组。
你有多个地方可以改变它,例如。 createConversation
, formattedConversations
,如果不查看您的实现代码就很难说,您也可以调试使用useConversation
的消费者组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.