使用“useState"挂钩时,有什么方法可以通过 React DevTools 查看 React 多状态中的“字段"名称 [英] Is there any way to see names of 'fields' in React multiple state with React DevTools when using 'useState' hooks

查看:129
本文介绍了使用“useState"挂钩时,有什么方法可以通过 React DevTools 查看 React 多状态中的“字段"名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习/试验 React 钩子.当我在 Chrome 中使用 React DevTools 检查组件当前状态的值时,我看到状态很好,但实际的字段"——即由各个 更新的状态变量useState 钩子——没有与它们关联的任何名称.相反,我看到,例如,几个字符串,几个布尔值等.我通常可以弄清楚发生了什么,但这似乎有问题——我希望能够看到哪个状态变量的名称是什么.

I've been learning/experimenting with React hooks. When I go to inspect the values of the current state of a component using React DevTools in Chrome, I see the state fine, but the actual 'fields' -- that is, the state variables that are being updated by the individual useState hooks -- don't have any name associated with them. Instead, I see, for example, several strings, a couple of booleans, etc. I can generally figure out what's going on, but this seems problematic -- I'd like to be able to see which what the state variable's name is.

例如,如果我有类似的东西

For instance, if I have something like

const [doughnuts, setDoughnuts] = useState(24)

当我查看 React DevTools 时,我希望看到类似doughnuts: number : 24"的内容,而不仅仅是number: 24".

When I look in React DevTools I'd like to see something like `doughnuts: number : 24', instead of just 'number: 24'.

我是否在某处遗漏了某些设置,或者某些开启此功能的技巧?

Am I missing some setting somewhere, or some technique to turn on this ability?

推荐答案

您没有遗漏任何东西,也无法改变这种行为.这就是 React 处理多个状态的方式.

You are not missing anything and you can't change this behaviour. This is how React deals with multiple state.

https://reactjs.org/docs/hooks-rules.html#explanation.

避免此问题的一种方法是使用单个 State Hook,它创建包含所有数据的单个状态.

One way to avoid this problem is to use a single State Hook which creates a single state including all the data.

const [state, setState] = useSate({doughnuts: 24, key1: 'value1', key2: 'value2'});

在这种情况下,状态存储在单个对象中,每个值都与一个键相关联.

In this case the state is stored in a single object and each value is associated with a key.

看看这个:我应该使用一个还是多个状态变量?

复合状态很难管理,但有一个工具可以帮助您:使用Reducer钩子

A compound state is hard to manage, but there is a tool which can help you with that: useReducer Hook

这篇关于使用“useState"挂钩时,有什么方法可以通过 React DevTools 查看 React 多状态中的“字段"名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆