react 如何调试
React 调试方法
使用 React Developer Tools 扩展
安装 Chrome 或 Firefox 的 React Developer Tools 扩展,可以查看组件树、状态、props 和 hooks。打开浏览器开发者工具后,切换到 "Components" 和 "Profiler" 标签页进行调试。
浏览器开发者工具
利用浏览器的内置开发者工具(如 Chrome DevTools)进行调试。在 "Sources" 标签页中设置断点,或使用 "Console" 查看日志输出。React 的错误和警告通常会显示在控制台中。
使用 console.log
在组件中插入 console.log 语句输出变量、状态或 props 的值。这是一种简单直接的调试方法,适合快速检查数据流。

function MyComponent(props) {
console.log('Props:', props);
const [state, setState] = useState(0);
console.log('State:', state);
return <div>{state}</div>;
}
使用 debugger 语句
在代码中插入 debugger 语句,浏览器会在执行到该语句时暂停,进入调试模式。可以在此时检查调用栈、变量和状态。
function MyComponent() {
const [count, setCount] = useState(0);
debugger; // 执行到这里会暂停
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
使用 Error Boundaries
通过实现 componentDidCatch 的 Error Boundary 组件捕获子组件树中的 JavaScript 错误,避免整个应用崩溃,并显示备用 UI。

class ErrorBoundary extends React.Component {
state = { hasError: false };
componentDidCatch(error, info) {
console.error('Error:', error, 'Info:', info);
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) return <div>Something went wrong.</div>;
return this.props.children;
}
}
使用 React Strict Mode
启用 StrictMode 可以帮助检测潜在问题,如不安全的生命周期方法或意外的副作用。它会触发额外的检查和警告。
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
使用 Jest 和 React Testing Library 进行测试
编写单元测试和集成测试可以帮助提前发现逻辑错误。使用 jest 和 @testing-library/react 测试组件行为和输出。
import { render, screen } from '@testing-library/react';
test('renders button', () => {
render(<MyComponent />);
expect(screen.getByRole('button')).toBeInTheDocument();
});
使用 Redux DevTools
如果项目使用 Redux 管理状态,安装 Redux DevTools 扩展可以查看 action 历史、状态变化和时间旅行调试。
性能分析
使用 React Profiler 或 Chrome 的 Performance 工具分析组件渲染性能,识别不必要的重新渲染或性能瓶颈。






