【问题标题】:TypeError: Cannot read property 'contacts' of undefinedTypeError:无法读取未定义的属性“联系人”
【发布时间】:2020-04-03 21:17:40
【问题描述】:

它只显示未定义的联系人。 我有 index.s,它是主要的 reducer,它指向联系 Reducer.js,我将提供者与我的组件 Contact.js 连接起来

Contacts.js index.js 的 maine 减速器 contactReducer.js 联系人缩减器

【问题讨论】:

  • 请发布实际代码而不是代码图片。
  • 你能把你的代码贴在codesandbox或类似的地方吗?
  • 你也可以发布 store.js 文件吗?

标签: reactjs redux react-redux reduce


【解决方案1】:

我的第一个想法是mapStateToProps 中的state.myContact 是未定义的。确保您正在创建商店并将其传递给您的 Provider。

来自文档的类似内容:https://redux.js.org/recipes/configuring-your-store/#configuring-your-store

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
import rootReducer from './reducers' <-- this is your main reducer index.js, where you export the combineReducers
import App from './components/App'

const store = createStore(rootReducer) <--- make sure you have this line

render(
  <Provider store={store}>             <-- and this line
    <App />
  </Provider>,
  document.getElementById('root')
)

您尝试使用联系人的第二个地方是在该行中

const { contacts } = this.props

如果this.props 未定义,则无法从中获取contacts

在 Contacts.js 中,您需要一个构造函数来确保定义了 props。添加一个调用super(props)的构造函数。

constructor(props) {
  super(props);
}

我在这里找到了信息:https://reactjs.org/docs/react-component.html#constructor

React 组件的构造函数在它被挂载之前被调用。在为 React.Component 子类实现构造函数时,您应该在任何其他语句之前调用 super(props)。否则,this.props 将在构造函数中未定义,这可能会导致错误。

这可能仅适用于您尝试在构造函数中使用道具的情况,因此这可能不是问题但值得一试。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-16
    • 2020-12-24
    • 2019-08-19
    相关资源
    最近更新 更多