[英]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.