太多的usestate -reccct

发布于 2025-02-13 08:00:36 字数 434 浏览 1 评论 0原文

我发现自己在反应功能组件中编写多个固定态脱酸。

const [option1, setOption1] = useState(false);
const [option2, setOption2] = useState(false);
const [option3, setOption3] = useState(false);
const [option4, setOption4] = useState(false);
const [option5, setOption5] = useState(false);

在Vue中,我可以做

const option = ref(true);

一些类似的反应,我可以在不使用usestate或巧妙地使用usestate的情况下创建一个反应性变量,在那里我可以结合强度的局部变量?

I am finding myselft writing multiple setState decalrations in React functional Component.

const [option1, setOption1] = useState(false);
const [option2, setOption2] = useState(false);
const [option3, setOption3] = useState(false);
const [option4, setOption4] = useState(false);
const [option5, setOption5] = useState(false);

In vue I can do

const option = ref(true);

Is there something similar in react where I can just create a reactive variable without usestate or a clever use of usestate where I can combine what is esentially just local variables?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

怪我入戏太深 2025-02-20 08:00:36

如果您的代码设置可以使用这些多个状态变量,则将它们组合到数组中不是问题。您现在不使用索引状态变量,因此我想使用此数组不需要一个(但我不知道您的代码的其余部分)。

只需尝试以下操作:

const [options, setOptions] = useState(new Array(5).fill(false))

要编辑此内容,您可以创建浅副本并更新所需的值,然后更新状态变量。

options_copy = [...options]
options_copy[0] = true
setOptions(options_copy)

希望这会有所帮助。

If you have your code setup to work with these multiple state variables, it shouldn't be a problem to just combine these into an array. You are not working with an index state variable right now, so you should not need one with this array I suppose (but I don't know the rest of your code).

Just try this:

const [options, setOptions] = useState(new Array(5).fill(false))

To edit this you can create a shallow copy and update the value you want and then update the state variable.

options_copy = [...options]
options_copy[0] = true
setOptions(options_copy)

Hope this helps.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文