简体   繁体   English

我在控制台中收到此错误:无法读取未定义的属性“ some”

[英]I am getting this error in the console : Cannot read property 'some' of undefined

TypeError: Cannot read property '' of undefined ı have no idea why ı am getting this error while I do check the code below everything seems fine :( trying to learn the way how react works :) So what is the purpose of this since all the properties I wrap on contextprovider suchas contacts loading and the functions I need TypeError:无法读取未定义的``属性''我不知道为什么ı在我检查下面所有代码的时候都会出现此错误:(试图了解反应的方式:)那么这的目的是什么我在contextprovider上包装的属性,例如联系人加载和我需要的功能

import React, { useState, useContext } from 'react'
import ContactContext from '../context/contactContext'

export default function ContactForm() {
  const name = useFormInput('')
  const email = useFormInput('')

  const contactContext = useContext(ContactContext)
  const { addContact } = contactContext

  const onSubmit = () => {
    addContact(name.value, email.value)
    name.onReset()
    email.onReset()
  }
  return (
   SOME HTML CODE HERE
  )
}

//contactState.js
import React, { useReducer } from 'react'
import _ from 'lodash'
import ContactContext from './contactContext'
import ContactReducer from './contactReducer'

const ContactState = props => {
  const initialState = {
    contacts: [
      {
        id: '098',
        name: 'Diana Prince',
        email: 'diana@us.army.mil'
      }
    ],
    loading: false,
    error: null
  }

  const [state, dispatch] = useReducer(ContactReducer, initialState)
  const [contacts, loading] = state
  const addContact = (name, email) => {
    dispatch({
      type: 'ADD_CONTACT',
      payload: { id: _.uniqueId(10), name, email }
    })
  }
  const delContact = id => {
    dispatch({
      type: 'DEL_CONTACT',
      payload: id
    })
  }
  return (
    <ContactContext.Provider
      value={{
        contacts,
        loading,
        addContact,
        delContact
      }}
    >
      {props.children}
    </ContactContext.Provider>
  )
}
export default ContactState

//contactReducer.js
export default (state, action) => {
  switch (action.type) {
    case 'ADD_CONTACT':
      return {
        contacts: [...state, action.payload]
      }
    case 'DEL_CONTACT':
      return {
        contacts: state.contacts.filter(
          contact => contact.id !== action.payload
        )
      }
    case 'START':
      return {
        loading: true
      }
    case 'COMPLETE':
      return {
        loading: false
      }
    default:
      throw new Error()
  }
}

//contactContext.js
import { createContext } from 'react'
const contactContext = createContext()
export default contactContext

In your reducer, when adding a contact, you're spreading the wrong state key. 在减速器中,添加联系人时,您散布了错误的状态键。 This should fix it: 这应该解决它:

case 'ADD_CONTACT':
  return {
    contacts: [...state.contacts, action.payload]
  }

I can't see where you are using ContactState in your app. 我看不到您在应用程序中使用ContactState的位置。 If you don't use it and render your ContactForm component with it then you can't reach any context value. 如果您不使用它并使用它呈现ContactForm组件,那么您将无法获得任何上下文值。 You should render it as: 您应该将其呈现为:

<ContactState>
  <ContactForm />
</ContactState>

in a suitable place in your app. 在您应用的合适位置。 Also, you can't get contacts and loading like that: 另外,您无法像这样获得contactsloading

const [ contacts, loading ] = state;

state is not an array, it is an object here. state不是数组,而是这里的对象。 You should use: 您应该使用:

const { contacts, loading } = state

You can find a simplified version of your code below. 您可以在下面找到代码的简化版本。 I removed/changed some parts in order to run it as much as possible. 我删除/更改了一些零件以便尽可能地运行它。 You should fix your reducer as @Asaf David mentioned in their answer, but this is not the main problem here. 您应该像@Asaf David在他们的答案中提到的那样来修复减速器,但这不是这里的主要问题。 After fixing the context issue, you can try to fix your reducer. 解决上下文问题后,您可以尝试修复减速器。

About your questions, if you try to understand how React works by looking at this example you can easily get confused. 关于您的问题,如果您通过查看本示例来了解React的工作方式,那么您很容易感到困惑。 Because Context is an advanced concept (at least for the beginners). 因为Context是一个高级概念(至少对于初学者而言)。 Also, the code uses useReducer with Context and this makes the things more complicated. 此外,代码将useReducerContext useReducer使用,这使事情变得更加复杂。 If your intent is to understand the React itself then start with the beginner guide . 如果您打算了解React本身,那么请从入门指南开始。

By using Context we can pass the data top-down to the deepest components. 通过使用上下文,我们可以将数据自上而下传递到最深层的组件。 But, in order to use that data those components should be rendered as children of the context provider. 但是,为了使用该数据,应将那些组件呈现为上下文提供者的子级。

In your code, you are doing this in ContactState but you never use it. 在您的代码中,您正在ContactState中执行此操作,但从未使用过它。 Also, in that component, you are defining a state with useReducer and feed your context with this state by value . 另外,在该组件中,您正在使用useReducer定义状态,并通过value将状态提供给上下文。

Finally, in your ContactForm component, you are using useContext hook to get the context data. 最后,在ContactForm组件中,您正在使用useContext挂钩来获取上下文数据。 In your current code since you don't render this component in a provider, contactContext is undefined and you are getting the error. 在当前代码中,由于未在提供程序中呈现此组件,因此contactContext是未定义的,并且会出现错误。 You can't get addContact from undefined. 您无法通过未定义获取addContact

In my example, I'm retrieving the contacts to show something. 在我的示例中,我正在检索contacts以显示某些内容。 Again, I've changed/removed some parts from your code. 同样,我已经从您的代码中更改/删除了某些部分。

 const { createContext, useContext, useReducer } = React; const ContactContext = createContext(); function ContactForm() { // Changed those values const name = ""; const email = ""; const contactContext = useContext(ContactContext); // changed addContact -> contacts const { contacts } = contactContext; const onSubmit = () => { addContact(name.value, email.value); name.onReset(); email.onReset(); }; // added some data to render return <div>{contacts[0].name}</div>; } function ContactReducer(state, action) { switch (action.type) { case "ADD_CONTACT": return { contacts: [...state, action.payload] }; case "DEL_CONTACT": return { contacts: state.contacts.filter( contact => contact.id !== action.payload ) }; case "START": return { loading: true }; case "COMPLETE": return { loading: false }; default: throw new Error(); } } const ContactState = props => { const initialState = { contacts: [ { id: "098", name: "Diana Prince", email: "diana@us.army.mil" } ], loading: false, error: null }; const [state, dispatch] = useReducer(ContactReducer, initialState); const { contacts, loading } = state; const addContact = (name, email) => { dispatch({ type: "ADD_CONTACT", // removed lodash part, added a static id payload: { id: 1, name, email } }); }; const delContact = id => { dispatch({ type: "DEL_CONTACT", payload: id }); }; return ( <ContactContext.Provider value={{ contacts, loading, addContact, delContact }} > {props.children} </ContactContext.Provider> ); }; // added the relevant render part ReactDOM.render( <ContactState> <ContactForm /> </ContactState>, document.getElementById("root") ); 
 <script src="https://unpkg.com/react@16/umd/react.development.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script> <div id="root" /> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我收到错误 Typerror 无法读取未定义的属性“执行” - I am getting an error Typerror Cannot read property 'execute' of undefined 为什么我越来越无法读取未定义错误的属性? - why I am getting, cannot read property of undefined error? 我收到错误“无法读取未定义的属性“用户名”” - I am getting the error "cannot read property "username" of undefined" 我收到一个错误:无法读取未定义的属性“推送” - I am getting an error: Cannot read property 'push' of undefined 当我可以打印未定义的变量时,为什么会出现“无法读取未定义错误的属性”? - Why Am I Getting “Cannot read property of undefined error” When I Can Print the Undefined Variable? 为什么会收到此错误类型错误:无法读取未定义的属性“客户端” - Why am getting this error TypeError: Cannot read property 'client' of undefined 我收到以下错误:错误TypeError:无法读取未定义的属性&#39;invalid&#39; - I am getting the following error: ERROR TypeError: Cannot read property 'invalid' of undefined 我为什么会收到TypeError:无法读取未定义的属性“现在” - Why am I getting TypeError: Cannot read property 'now' of undefined 为什么我在此 for 循环中无法读取未定义的属性“startsWith”? - Why am I getting Cannot read property 'startsWith' of undefined in this for loop? 为什么会出现“无法读取未定义的html属性”? - Why am I getting “Cannot read property of html undefined”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM