reactjs - Reset React contexts after use
问题描述
In my project, there are several elements rendered in the page. I've been using useContext to update certain elements when changes occur. For example, when the user edits a role with the EditRole component, the updatedRole context is set to that role's new value. The RoleList component has a useEffect that runs when updatedRole changes. It checks if the context has an id attribute. If it does, it searches the list for the old role and updates it. Afterwards, the context is set an empty object, the same as its default value.
However, there are cases in which the two useStates that should run based on the same context. The problem is that I'm not sure if, by setting a context to an empty object in one useEffect, the other one will be affected. And if it isn't affected, I won't be sure if that was just an exception (like, if was a variation in processing speed or order, or something of the sort).
Do the multiple sets make any difference, and, if it does, what should I do?
Here is the part of the code in RoleEdit.js that sets the context.
const response = await api.put
(
"/groupidupdatesimp",
{
name: group.name,
roles: group.roles,
owner: currentCentral._id
},
{
params:
{
_id: group._id
}
}
);
if (response.data === "")
{
setMessage (`Já existe um grupo com o nome ${group.name}.`);
}
else
{
setUpdatedGroup (group);
setMessage (`O grupo ${group.name} foi atualizado.`);
}
Here is the part of the code in RoleList.js that uses the context.
useEffect
(
() =>
{
if (updatedGroup.hasOwnProperty ("_id"))
{
groups.map
(
(group, index) =>
{
if (group._id === updatedGroup._id)
{
var tempGroup = groups;
tempGroup[index] = updatedGroup;
setGroups (tempGroup);
setUpdate (update+1);
}
}
)
}
},
[updatedGroup]
);
解决方案
推荐阅读
- r - 查找公共和唯一数字并将它们放入 R 中的新整数向量中
- validation - WTForms 和 Flask - 在另一个字段中验证文件大小
- javascript - reactjs中如何进行路由
- python - Pandas - 如何按日期选择事件并创建新的有序数据框。- 手术患者
- c# - 在C#中从串口接收数据,同时更新ui
- c# - 在 .NET MVC 应用程序中从静态方法更改为非静态方法
- javascript - 基于无线电选择的隐藏类
- java - 如何决定一组标记何时应该成为一个集群?
- c++ - 带有向量的移动与复制构造函数
- ubuntu - shellscript的crontab