首页 > 解决方案 > 为什么我需要为动作创建者添加花括号?

问题描述

动作创建者:

export const addTodoCustom = function (text) {
    return {
        type: "ADD_TODO",
        id: nextTodoId++,
        text
    };
};

正确的说法:

import * as actions from "../actions"
import AddTodo from "../components/AddTodo";
import {bindActionCreators} from "redux";
import {addTodoCustom} from "../actions";


export default connect(mapStateToProps, {addTodoCustom})(AddTodo);

错误的说法:

export default connect(mapStateToProps, addTodoCustom)(AddTodo);

为什么我需要在 React with Redux 中为动作创建者添加花括号?Javascript的语法是什么?

更新:

示例项目: https ://github.com/gongzelong0718/redux-quickstart-tutorial/tree/question

注:请查看分行question

错误语句运行时错误截图

更新 2

这是我的想法:

我检查了 JavaScript ES6 语法:Enhanced Object Literal Value Shorthand

正确的陈述等于:

export default connect(mapStateToProps, {a: addTodoCustom})(AddTodo);

那么为什么我需要使用{a: addTodoCustom}而不是addTodoCustom

标签: javascriptreactjsreact-redux

解决方案


First, you need to import your connect function before you can use it like so:

import { connect } from 'react-redux';

With the connect helper you can pass up to two arguments to it, the first one being either null or mapStateToProps, but you have to create that function first. Its purpose is to take your global state object (application state), the thing that sits inside your Redux store and map it or take some properties off the state object and provide them as props to your component of AddTodo.

I think you are also missing your payload property, so instead you want your action creator to look like so:

export const addTodoCustom = text => {
   return {
     type: "ADD_TODO",
     id: nextTodoId++,
     payload: text
   };
};

It would have been helpful I think for you to also post your reducer, since this is all part of the Redux system.

Now back to your connect() function, the second argument would be the action creator that you want to bind to that component which would be addTodoCustom. Please ensure that your relative path to it in your import statement is correct.

Once having done all the above then this export default connect(mapStateToProps, {addTodoCustom})(AddTodo); should work as long as you have your mapStateToProps function. If not then you need to write it like this: export default connect(null, {addTodoCustom})(AddTodo);

You never showed the contents of your AddTodo component, and one can only assume by the use of mapStateToProps that it is a class-based component, it would be helpful if you shared that code as well.


推荐阅读