Thanks to chrome’s debugging capabilities, console.log is the most straightforward way to solve an unknown problem in front-end development. However, there is a better debugging solution in the React project. That is the official React DevTools (Facebook), which can do some specific code debugging. If you want to try react DevTools, check out this article to see what the tool can do. (Long warning, please Mark 👍)
Install & open ⚒
The installation
React DevTools was introduced as a browser plugin in the React Project on the Web. You can add the react DevTools plugin in Chrome and firefox. Go to the menu ->Web Developers -> Get more Tools -> search for “React Developer Tools”- > Install
chrome: firefox:
To open the Chrome Web store, you may need scientific Internet access, while Firefox does not need scientific Internet access to install plug-ins, and use the same
Tool entrance
If the react project is detected, the tool icon in the upper right corner (right side of the address bar) will change to:
Debug version of react project, coding👨🏻💻
A production version of React has been packaged and released
React indicates that the current version of react is older and usually appears in Act15 or earlier versions
There are no react dependencies detected in the Web ❌
React DevTools allows you to use ⚛️ Components and ⚛️ Profiler tabs at the end of the debugger.
JSX structure tree 🌲
To facilitate the demonstration function, here is a commonTable showsandThe search function, the component level isUser
There are two components under the componentUserSearch
和 UserList
Components.
positioning
JSX
是 React
Key points in grammar,Components
The tools are also a big part of the presentationreact
的 JSX
virtualDom
Tree, the pick icon in the upper left corner is used withchrome devtools
The pick is the same, click to locate the specific component you want to see details.
Locate theUserSearch
component
I used some in the projectReact-router
, redux
Wait for tools after virtualDom
Trees can be invaded, for exampleDom
A little bit more in the treeConext.Consumer
And these arecontext
In spite of these structures,Double click on theThe target component can be drilled into the detailed structure of the component, for example, by double-clickingUser
Components:Isn’t that much clearer,User
Under aSuspense
, Suspense
There are two custom components, highlighted in red globallyDom
All the levels in the tree.
Suspense is used with the react lazy loading, document: zh-hans.reactjs.org/docs/code-s…
The filter
Another trick is to easily filter out those that do not want to show the Dom. Click on the setting widget, and there is a drop-down bar for component Settings. Then go to “Hide Components Where “and add a filter to filter the Dom. Here is a list of what each configuration represents.
Filter first column key:
The name of the | meaning |
---|---|
location | Router Indicates the component that matches the route |
name | Group price |
type | Breakdown of various component types (refer to table below) |
hoc | High order component |
Location and name are both reged-matched
Type Optional value:
The name of the | meaning |
---|---|
class | Class component that inherits react.component.component.class |
context | Shared context Context |
function | Functional component |
forward ref | Functional components pass Ref’s HOC |
host(e.g
)
|
Browser supported HTML elements, div, H1, P |
memo | Functional components do props optimized HOC |
other | Others ❓ (to be added) |
profiler | performance-measuring |
suspense | Lazy loading of the root component |
Single component debugging 🔧
After locating the target component, you can perform single-component debugging. Double-click on the component. On the right side of react DevTools, information about the component is displayed, such as props, State, hooks, and Render by.
从 props
You can see that,User
Component isRouter
The first tier of components below will havelocation
, history
, match
For additional information.
The root state of the hooks is missing the attribute name. For the time being, useState
Light can not be used to see attributes, but only to see and use them. Careful digging has found a row of ICONS in the upper right corner:
1. The lazy fallback status is displayed
In Suspense, the timing button is related to lazy loading. When children in Suspense components are not loaded, there is a loading effect. In Suspense, clicking the button will show the ReactNode in fallback. It’s a good way to preview loading.
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>} ><OtherComponent />
</Suspense>
</div>
);
}
Copy the code
Here, the Skeleton effect of ANTD is introduced as the intermediate state of loading. The small icon highlighted indicates that the state is in loading state.
2. Check the actual Dom of the component
inReact
Writing in theJSX
None of the component trees rendered by the code are actually realDOM
Trees, so there areDebugging style,Modify the documentDirect operationDOM
Demand, or need to cut backchrome devtools
的 Element
And then locateElement
Another pick up operation is slightly inconvenient, and the button with the little eye icon is used to locate the component’s real Dom.Here byUserSearch
The component is located to the realdom
Trees, for some of the deeper levelsdom
Structure, orz-index
This feature location is quite convenient for dom hierarchies.
3. The debug information
The bug button will be very confusing at the beginning of the use, after clicking it seems to have no effect, then hover for a moment will have a text:
Log this component data to the console
Then switch to the Chrome DevTools console and you’ll see the component information associated with UserSearch:
According to the prompts,Right clickAny value, then click “Store as global variable” and save asThe global variableSo, we’re choosing hereProps
Under theonSearch
Methods:
console
A new one will appear intemp1
The variable, the variable is pointingonSearch
Call to the reference value oftemp1
The function is equivalent toonSearch
, onSearch
The business logic is based on parametersfilterUser list, here is the filter to contain “xu” records:
This kind ofdebug
Method is convenient in some special scenarios, such as through ordinary page interaction cannot trigger, needThe asynchronous interfaceThe return value is triggered and so on.
4. Locate source-map information
The last button is very familiar, usually in someComponent library documentationCode examples, such asantd
, fusion
, iview
And other UI component libraries that serve as debug portals for unwrapping code,react devtools
The function is similar, here is to locate the corresponding componentSource
Files, I’m going to switch over hereUserSearch
The correspondingindex.tsx
File, configured in the development environmentsource-map
, positioning components can be displayed directlyThe source code.Here,source
It’s very powerful, and the most commonly used isBreaking pointFor example, we areresetTrigger
There are two breakpoints in the breakpoint, click reset button will trigger the breakpoint:
The Scope in the right pane contains closure information, which is actually generated by the useState API to save functional components, and filter is the content of the input box. This debugging can avoid the need to recompile the project after console.log changes the code. You might also leave some dirty code behind.
Performance problem tracking 🚥
The React profiler API can be added anywhere in the React tree to measure the overhead incurred by rendering parts of the tree. The profiler API can be added anywhere in the tree to measure the overhead incurred by rendering parts of the tree.
render(
<App>
<Profiler id="Navigation" onRender={callback}>
<Navigation {. props} / >
</Profiler>
<Main {. props} / >
</App>
);
Copy the code
The input parameter of the onRender callback contains all the rendering information of the subcomponent, which is helpful for checking the performance of the component:
function onRenderCallback(
id, // The "ID" of the Profiler tree in which the commit occurred
phase, // one of "mount" (if the component tree was just loaded) or "update" (if it was rerendered)
actualDuration, // Committed The committed rendering time
baseDuration, // Estimate the time required to render the entire subtree without memoization
startTime, // React starts rendering time in this update
commitTime, React COMMITTED time in this update
interactions // This is the set of interactions
) {
// Add up or record render times...
}
Copy the code
The official document links: zh-hans.reactjs.org/docs/profil…
Although debugging in a project is flexible, it can cause code intrusion and even performance degradation. Therefore, when using a global profiler, you can first try using the Profiler function of React DevTools.
Now to test this outprofiler
Function,UserList
Ten thousand records have been added to the component to show how much time it takes:Here is a typical performance analysisFlame figure, shows the time consumption of each component in the current page. If there is an abnormal component that consumes a long time, the horizontal bar chart will display asyellowAnd even more alarming 🚨 colors, which are obvious here,UserList
“Took quite a long time, which was in line with our expectations.
inprofiler
System Settings, can also turn on components when to render switches, as wellhiddenFixed render time for the following components:
Why did this renderRoute
The component was rendered for the first time, rendering for 12.8 milliseconds
End ⌛ ️
React Devtools provides you with a tutorial on how to debug react Devtools. You can use 👇 to learn how to debug react Devtools.
portal
PS: If there are any mistakes in this article, please kindly correct them
Past wonderful 📌
- Vue3 hugs TypeScript properly ✨
- Vue3-one piece尝鲜:React Hooks VS Composition API ✨
- Optimize performance ✨