英文:
Must parameter passing into dispatch function be Object which containt 'type' property in reactjs
问题
我正在学习在Reactjs中使用useReducer。在教学视频或关于useReducer Hook的文档中,传递给dispatch函数的参数总是一个常规的JavaScript对象(其中包含type属性和其他信息,帮助在reducer函数中设置新状态)。
我有一个问题,即在Reactjs中将对象作为参数传递给dispatch函数是Reactjs的规则还是Reactjs开发人员交流的编码约定。此外,除了将对象作为参数传递给dispatch函数外,我是否可以根据需要将任何数据类型传递给dispatch函数?
英文:
i am learning about useReducer in Reactjs. In teaching video or documentation about useReducer Hook, parameter passed into dispatch function is always a regular JavaScript object (which contain type property and other infor helping to set new state in reducer function).
I have a question that passing object as parameter to dispatch function in reactjs is the rule of Reactjs or it is a coding convention of reactjs dev communication. In addition, instead of passing object as parameter to dispatch function, can i pass whatever data's type as i want to dispatch function?
答案1
得分: 1
从将状态逻辑提取到Reducer中文档中:
> 动作对象可以有任何形状。
> 通常,按照惯例,将为其提供描述发生了什么的字符串 type
,并在其他字段中传递任何附加信息。
这是一种约定,不是限制也不是强制性的。
以下是一些最佳实践:
- Flux标准动作
- 不要将不可序列化的值放入状态或动作中
- 使用Flux标准动作约定编写动作。优先使用FSA格式的动作以保持一致性。
查看此测试用例:双重调用Reducer函数
您将找到 dispatch(1)
,此测试用例调度了一个原始数字。
查看源代码,action
将会传递到Reducer函数此处。
React v16.14.0
// ...
const currentState: S = (queue.lastRenderedState: any);
const eagerState = lastRenderedReducer(currentState, action);
// ...
英文:
From the Extracting State Logic into a Reducer documentation:
> An action object can have any shape.
> By convention, it is common to give it a string type
that describes what happened, and pass any additional information in other fields.
It's a convention, not restrictive nor mandatory.
Here are some best practices:
- Flux Standard Action
- Do Not Put Non-Serializable Values in State or Actions
- Write Actions Using the Flux Standard Action Convention. Prefer using FSA-formatted actions for consistency.
See this test case: double invokes reducer functions
You will find dispatch(1)
, this test case dispatches a primitive number.
Take a look at the source code, the action
will be pass-through to the reducer function here.
React v16.14.0
// ...
const currentState: S = (queue.lastRenderedState: any);
const eagerState = lastRenderedReducer(currentState, action);
// ...
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论