javascript - 为什么我需要为动作创建者添加花括号?
问题描述
动作创建者:
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
?
解决方案
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.
推荐阅读
- xamarin - 如何在自定义 webview xamarin 表单中显示 pdf
- ember.js - Ember 客户端部署不部署更改
- c++ - 通过迭代器打印出地图的值
- linux - 更改 nginx 的日志文件位置
- laravel - 如何在 Vue 搜索组件中显示子嵌套数组 - Laravel
- c - 为什么在 q==p 的情况下,memcmp 实现不快捷 memcmp(q, p, n)?
- php - 运行 composer dump-autoload 后未找到迁移事件
- c# - 如何将三元运算符(?:)与 break 关键字一起使用
- javascript - Javascript - 如何从数组列表中获取最后一条记录?
- java - RecylerView 项目折叠数据显示