参数传递到ReactJS的dispatch函数中必须是包含’type’属性的对象。

huangapple go评论60阅读模式
英文:

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,并在其他字段中传递任何附加信息。

这是一种约定,不是限制也不是强制性的。

以下是一些最佳实践:

查看此测试用例:双重调用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:

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);
// ...

huangapple
  • 本文由 发表于 2023年6月29日 14:48:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76578642.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定