【问题标题】:mapStateToProps() in Connect() must return a plain object. Instead received undefinedConnect() 中的 mapStateToProps() 必须返回一个普通对象。而是收到未定义的
【发布时间】:2019-03-08 11:11:15
【问题描述】:

我在显示数据时遇到问题。

在我的应用程序中,我使用 react 和 redux。

在控制台我会收到一个错误mapStateToProps() in Connect(ListPets) must return a plain object. Instead received undefined.

这是我的主要组件

import React, { Component } from 'react';
import { connect } from 'react-redux';
import loadData from '../actions/actions';

class ListPets extends Component {

  componentDidMount() {
    const { loadData } = this.props;
    loadData();
    console.log(loadData );
  }

  render() {
    const { dataPet } = this.props;
    return (
      <div>


      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return state;
};

const mapDispatchToProps = (dispatch) => {
  return {
    loadData: () => dispatch(loadData())
  }
};

这个片段console.log(loadData );显示

ƒ loadData() {
      return dispatch(Object(_actions_actions__WEBPACK_IMPORTED_MODULE_7__["default"])());
    }

当我在 div 中添加代码 {dataPet.data} 时。我得到一个错误]。好像这个数据不在商店里,我不知道......

这是我的减速器功能

const initialState = {
  isFetching: false,
  dataPet: [],
};

const fetchDataReducer = (state=initialState, action) => {
  switch(action.types) {
    case actionTypes.FETCH_DATA_START:
      return {
        ...state,
        isFetching: true,
      }
    case actionTypes.FETCH_DATA_SUCCESS:
      return {
        ...state,
        isFetching: false,
        dataPet: action.dataPet,
      }
    case actionTypes.FETCH_DATA_FAIL:
      return {
        ...state,
        isFetching: false,
      }
  };
}

数据很好下载,因为控制台收到了FETCH_DATA_SUCCESS 操作。

我不知道如何解决这个问题

【问题讨论】:

  • @HemadriDasari 这是我的代码 codesandbox.io/embed/rj4yz06xqm?fontsize=14

标签: reactjs redux


【解决方案1】:

我对您的代码进行了一些更改,现在试试这个...应该可以 https://codesandbox.io/s/z2volo1n6m

【讨论】:

  • 在reducer中你使用action.types,你需要使用action.type....我改变我的codesandbox
【解决方案2】:

在你的减速器中你有一个错字:

const fetchDataReducer = (state=initialState, action) => {
  switch(action.types) { // here

应该是action.type 而不是action.types

【讨论】:

    【解决方案3】:

    如果thing 是处于状态的对象:

    const mapStateToProps = state => ({
      thing: state.thing,
    });
    

    然后使用like:

    this.props.thing 在你的组件中

    【讨论】:

    • 我更新了---- const mapStateToProps = state => ({ dataPet: state.dataPet, }); ----但我收到此错误----TypeError:无法读取未定义的属性'dataPet'----
    • 你安装了 Redux 开发工具吗?你能验证状态是否在你期望的结构中?
    • 我有 redux-logger。当我有这个 --- const mapStateToProps = state => ({ state }); ---- 我得到动作 FETCH_DATA_SUCCESS @ 12:21:07.618
    • 你可能想设置一个 CodeSandbox 演示......我的感觉是状态没有更新。
    猜你喜欢
    • 1970-01-01
    • 2016-10-01
    • 2018-04-27
    • 2019-02-14
    • 2016-06-22
    • 1970-01-01
    • 2017-07-08
    • 2017-06-06
    • 2018-09-10
    相关资源
    最近更新 更多