如何将React.Component转换为纯函数?Airbnb ESLint配置提示需使用纯函数替代React组件
Fixing the
react/prefer-stateless-function ESLint Warning Hey there! That ESLint warning is popping up because your App component is a class that only has a render method—no state, no lifecycle hooks, no instance methods. This makes it a perfect candidate for a pure function component, which is more concise and aligns with modern React best practices.
Here's how to convert your class component to a pure function:
Step-by-Step Conversion
- Remove the class definition: Replace
class App extends Componentwith a function declaration (arrow function or regular function both work). - Get rid of the
rendermethod: Pure function components return JSX directly, so you can eliminate therender()wrapper. - Clean up imports: You won't need to import
Componentfrom React anymore, just keep the core React import (and your route/component imports, of course).
Converted Code
import React from 'react'; import { Router, Routes, Route } from 'react-router-dom'; import NavBar from './NavBar'; import HomePage from './HomePage'; import SignUp from './SignUp'; import ProfilSetting from './ProfilSetting'; import Footer from './Footer'; const App = () => { return ( <Router> <div className="App"> <NavBar /> <Routes> <Route exact path="/" element={<HomePage />} /> <Route path="/signup" element={<SignUp />} /> <Route path="/profilsetting" element={<ProfilSetting />} /> </Routes> <Footer /> </div> </Router> ); }; export default App;
Quick Notes
- If you prefer regular function syntax instead of arrow functions, this works too:
function App() { return ( // Same JSX as above ); } - If you ever need to add props to this component later, just add them as a parameter to the function:
const App = (props) => { ... } - Pure function components are lightweight and easier to read, which is why ESLint (and the React team) recommend them for components that don't need class-specific features.
内容的提问来源于stack exchange,提问作者Kelijsto
相关产品推荐
相关产品推荐

