(一)初始化项目
1.安装项目
npx create-react-app 项目名
编译报错:
解决办法:安装最新的babel-preset-react-app
npm install babel-preset-react-app@latest
2.配置项目
(1)配置文件目录
(2)使用craco配置webpack.config
npm install @craco/craco -D
配置别名alias
// craco.config.js
const path = require('path')
// 解析绝对路径
const resolve = (pathname)=>path.resolve(__dirname,pathname)module.exports = {// 配置webpackwebpack:{// 配置别名alias:{'@':resolve('src'),}}
}
更改package.json打包命令
react-scripts不会解析craco的配置,使用craco命令运行会自动执行craco配置,再与webpack配置合并
更改为:
这样路径别名就没有报错啦!
(3)配置less
下载less和craco-less
npm i less craco-less -D
在craco.config配置less
// craco.config.js
const CracoLessPlugin = require('craco-less')module.exports = {// 配置lessplugins: [{plugin: CracoLessPlugin,options: {lessLoaderOptions: {lessOptions: {modifyVars: {},javascriptEnabled: true,}}}}],
...
重新启动,使用下!没报错 !
(4)重置和初设样式
下载normalize.css
npm i normalize.css
引入:
// App.jsx
import "normalize.css"
设置变量样式variable.less
设置自定义预设样式reset.less
(二)配置router
在这个项目里还是采用6.2的写法,就不写6.4的了
安装router
npm i react-router-dom
采用history路由
// index.jsx
import { BrowserRouter } from 'react-router-dom';const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<React.StrictMode><BrowserRouter><App /></BrowserRouter></React.StrictMode>
);
在App.jsx中引入路由
本来应该是用<Routes><Route />...</Routes> 这种结构的,为了把路由结构剥离出来单独放在router文件夹中,使用useRoutes hook解析routes数组
// app.jsx
import { useRoutes } from 'react-router-dom'
import routes from './router'
import Header from './components/Header'
import Footer from './components/Footer'const App = memo(() => {return (<div className='app'><div className='header'><Header /></div><div className='content'>{useRoutes(routes)}</div><div className='footer'><Footer /></div></div>)
})
编写路由routes
这样看的话其实跟6.4的差别不大,跟vue-router越来越相似了
// router/index.jsx
import { Navigate } from "react-router-dom"
import { lazy } from "react"
// 懒加载
const Home = lazy(() => import('@/views/home'))
const Detail = lazy(() => import('@/views/detail'))
const More = lazy(()=>import('@/views/more'))const routes = [{path:'/',element:<Navigate to="/home" /> // 重定向},{path:'/home',element:<Home />,},{path:'/detail',element: <Detail />,},{path:'/more',element: <More />,},
]export default routes
})
好了就是这样了!
但是会报警告:
(三)配置redux
1.安装redux
npm i @reduxjs/toolkit react-redux
2.创建store
创建
// store/index.js
import { configureStore } from "@reduxjs/toolkit";const store = configureStore({reducer:{}
})export default store
引入
// index.js
import { Provider } from 'react-redux'
import store from './store'const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<React.StrictMode><Provider store={store}><BrowserRouter><App /></BrowserRouter></Provider></React.StrictMode>
);
3.引入slice
在store的modules文件夹下创建各个组件的reducer切片
// store/modules/home.js
import { createSlice } from "@reduxjs/toolkit";const homeSlice = createSlice({name:'home',initialState:{},reducers:{}
})export default homeSlice.reducer
导入到store
import { configureStore } from "@reduxjs/toolkit";
import homeReducer from './modules/home'const store = configureStore({reducer:{home:homeReducer,}
})export default store
先就这样,等有数据需要处理的时候再继续写
(四)配置axios
下载axios
npm i axios
先建立这样的文件结构
- modules:存放各模块的接口信息
- request:配置二次封装axios
- index.js:封装请求对象的出口
在request/config.js配置axios配置项
// 请求路径
export const BASE_URL = 'http://codercba.com:1888/airbnb/api'
// 请求限制时间
export const TIMEOUT = 1000 * 10
在request/index.js封装axios
// 对axios二次封装
import axios from "axios";
import { BASE_URL, TIMEOUT } from "./config";class HYRequest{constructor(baseURL, timeout){this.instance = axios.create({baseURL:baseURL,timeout:timeout,})// 响应拦截this.instance.interceptors.response.use(res=>{return res.data},err=>{return err})}request(config){return this.instance.request(config)}// 封装get get(config){return this.request({...config,method:'get'})}// 封装post post(config){return this.request({...config,method:'post'})}
}
// 导出实例
export default new HYRequest(BASE_URL,TIMEOUT)
导出到出口文件:
import hyRequest from './request'export default hyRequest
拿home组件试试请求能不能成功
import React, { memo, useEffect } from 'react'
import hyRequest from '@/service'const Home = memo(() => {useEffect(()=>{hyRequest.get({url:'/home/highscore'}).then(res=>{console.log(res);})},[])return (<div>Home</div>)
})export default Home
拿到数据了,搞定