【问题标题】:mapStateToProps() in connect() must return a plain object, Instead received Undefinedconnect() 中的 mapStateToProps() 必须返回一个普通对象,而不是收到 Undefined
【发布时间】:2018-10-01 12:14:58
【问题描述】:

我已经实现了 redux 来完成一个 TODO 应用程序。

我的待办事项代码

 import { connect } from "react-redux";

import TodoList from "../components/TodoList.js";

// Here we will connect 

const mapStateToProps = state => {
    todos: state.todos
}

const mapDispatchToProps = dispatch => {
    toggleTodo: id => dispatch({ type: 'TOGGLE_TODOS', id })


}


export default connect(mapStateToProps, mapDispatchToProps)(TodoList);

// 减速器

 const todos = (state = [], action) => {
    switch (action.type) {
        case 'ADD_TODO':
            return [
                ...state, {
                    id: action.id,
                    text: action.text,
                    visibility: false
                }
            ]
        case 'TOGGLE-TODO':
            return state.map(todo => (todo.id === action.id)
                ?
                { ...todo, completed: !todo.completed }
                : todo)
        default:
            return state;
    }

}

export default todos;

最后我得到一个错误 'mapStateToProps 必须接收普通对象,而不是接收未定义'。

请告诉我如何解决这个问题。

【问题讨论】:

  • 请将您的减速器添加到帖子中。
  • 请检查更新的问题
  • 您没有返回对象:const mapStateToProps = state => ({ todos: state.todos });。注意括号。或者const mapStateToProps = state => { return { todos: state.todos }; };

标签: react-native redux react-redux


【解决方案1】:

你需要返回对象,你可以这样做,看对象周围的括号。

const mapStateToProps = state => ({
    todos: state.todos
})

你也可以

const mapStateToProps = state => { 
    return { todos: state.todos }; 
};

两者都返回一个对象。

【讨论】:

    【解决方案2】:

    你有一个语法错误。您应该将代码括在括号中。

    const mapStateToProps = state => ({
        todos: state.todos
    })
    

    简而言之:

    const mapStateToProps = state => ( { } ) // This returns an empty object
    

    【讨论】:

    • 感谢分享空对象。那是为我做的。
    【解决方案3】:

    对我来说,问题在于 import 声明不正确。

    在我的代码中是

    ...
    import { parseStore } from "../../parseStore"; // cause of ERROR
    import reducer from "../../reducer";
    
    const mapStateToProps = () => {
      return parseStore;
    };
    
    ...
    

    导入失败并导致undefined。通过将导入语句从命名导入更正为默认导入来解决它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-14
      • 2016-06-22
      • 2016-10-01
      • 2018-04-27
      • 1970-01-01
      • 2017-08-18
      • 1970-01-01
      • 2021-04-01
      相关资源
      最近更新 更多