sak*_*eth 5 reactjs react-redux
我真的对这段代码感到困惑。我只想知道我们如何将参数传递给reducer(state, action)函数。我的主要问题是:action 参数如何发送到我的 Comments.js 文件中的 reducer 函数?我什至没有导入 ActionCreator.js 文件,但我能够使用和评论返回的有效负载值。这怎么可能?有人,请以透明的方式向我解释这一点。
请原谅我的代码片段编辑
/ActionTypes.JS
export const ADD_COMMENT='ADD_COMMENT';
/ActionCreator.js
import * as ActionTypes from './ActionTypes';
export const addComment=(dishId, rating, author, comment)=>({
type:ActionTypes.ADD_COMMENT,
payload:{
dishId:dishId,
rating:rating,
author:author,
comment:comment
}
})
/Comments.js
import {COMMENTS} from "../shared/comments";
import * as ActionTypes from "./ActionTypes"
export const Comments=(state=COMMENTS, action)=>{
switch(action.type){
case ActionTypes.ADD_COMMENT:
var comment=action.payload;
comment.id=state.length
comment.date=new Date().toISOString()
console.log("Comment" + comment)
return state.concat(comment)
default:
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
当您配置了 redux 存储时,您必须通过减速器来存储像这里一样。现在,如果您在示例中看到,他们正在调用store.dispatch(<some_action>). 基本上现在你的商店知道所有的减速器都在那里,它调用每个减速器,并使用在调度函数中传递的有效载荷并返回一个更新的存储。但最有可能的是,您不是store.dispatch()直接调用,您必须使用connect()来访问 store。正如这里提到的,它将您的组件连接到您的 redux 存储,现在您不必调用store.dispatch相反,您可以直接访问 dispatch 函数,您可以在其中传递有效负载,并且继续执行与第一个示例中相同的过程。您不必导入调用缩减程序,redux 会为您完成。希望这能让事情清楚。
| 归档时间: |
|
| 查看次数: |
918 次 |
| 最近记录: |