前言
记录react18的学习历程。
项目搭建
- 使用官方推荐脚手架搭建单页面应用
npx create-react-app react-front
cd react-front
npm start
react-router
yarn add react-router react-router-dom
code
import React from 'react';
import ReactDOM from 'react-dom/client';
import { BrowserRouter, Routes, Route } from 'react-router-dom';
import './index.css';
import App from './App';
import Home from './views/home/index';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<BrowserRouter>
<Routes>
<Route path="/" element={<App />}></Route>
<Route path="Home" element={<Home />} />
</Routes>
</BrowserRouter>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
此时:打开localhost:3000/home,可看到home的内容。
- home自己随便写吧。
思考
- 1.现在没有入手写node接口是否使用mock
- 2.路由已经能跳转了,如何实现登录后多角色页面权限的功能。
- 3.最近新看到的css库Tailwind CSS是否要一起实践。
mock
- 引入mock
yarn add mockjs
- 在src新建文件mock(我在src外新建后无法引入)
import Mock from 'mockjs';
const getList = Mock.mock('/api/getList', 'post', {
success: true,
data: [{ name: 'wb' }],
});
- 安装axios
yarn add axios
- 新建request/index.js,axios 拦截器。
import axios from 'axios';
// 创建实例时配置默认值
const instance = axios.create({
baseURL: '/api',
});
instance.defaults.timeout = 2500;
instance.interceptors.request.use(
(config) => {
// 在发送请求之前做些什么
return config;
},
(error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
);
// 添加响应拦截器
instance.interceptors.response.use(
(response) => {
// 2xx 范围内的状态码都会触发该函数。
// 对响应数据做点什么
return response;
},
(error) => {
// 超出 2xx 范围的状态码都会触发该函数。
// 对响应错误做点什么
return Promise.reject(error);
}
);
export default instance;
- 创建api/index.js
import request from '../request/index';
import mock from '../mock/index';
export const getList = () => {
return request({
url: '/getList',
method: 'post',
});
};
- 测试(home中调用接口)
import React, { useEffect } from 'react';
import { getList } from '../../api/index';
const home = () => {
useEffect(() => {
getList().then((res) => {
console.log(res, 'res');
});
});
}
- 此时已经能拿到数据了。
- Tailwind CSS下篇文章浅析。
我正在参加「创意开发 投稿大赛」详情请看:掘金创意开发大赛来了!