react项目如何
创建React项目
使用Create React App(CRA)快速初始化项目,确保已安装Node.js(建议版本≥16)。通过以下命令创建项目:
npx create-react-app my-app
cd my-app
npm start
项目结构优化
删除不必要的初始文件(如reportWebVitals.js),按功能模块组织目录。典型结构示例:
src/
├── components/ # 通用组件
├── pages/ # 页面级组件
├── hooks/ # 自定义Hook
├── utils/ # 工具函数
└── App.js # 根组件
状态管理选择
小型项目可使用React Context + useReducer:
const AppContext = React.createContext();
function AppProvider({children}) {
const [state, dispatch] = useReducer(reducer, initialState);
return <AppContext.Provider value={{state, dispatch}}>{children}</AppContext.Provider>;
}
大型项目推荐Redux Toolkit:
npm install @reduxjs/toolkit react-redux
路由配置
安装React Router v6:
npm install react-router-dom
基本路由配置示例:
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
样式方案
CSS Modules方案(无需额外安装):
/* Button.module.css */
.primary { background: #007bff; }
import styles from './Button.module.css';
<button className={styles.primary}>Click</button>
或使用TailwindCSS:
npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init
数据请求
推荐使用axios:
npm install axios
封装API请求模块:
// api.js
import axios from 'axios';
export const fetchUser = () => axios.get('/api/user');
性能优化
使用React.memo避免不必要的渲染:
const MemoComponent = React.memo(function Component({prop}) {
return <div>{prop}</div>;
});
代码分割动态导入:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
<Suspense fallback={<Spinner />}><LazyComponent /></Suspense>
测试配置
安装测试工具链:
npm install --save-dev jest @testing-library/react
编写组件测试:
test('renders button', () => {
render(<Button />);
expect(screen.getByRole('button')).toBeInTheDocument();
});
生产构建
生成优化后的生产包:
npm run build
部署到静态服务器:
npm install -g serve
serve -s build






