步骤
1. 起步(脚手架创建项目)
create-react-app 项目名
2. 配置跨域
- 打开Create React App脚手架中文文档:https://create-react-app.bootcss.com/
- 打开菜单“服务端集成-Proxying in Development”,这页文档记录了跨域如何配置
步骤: - 安装http-proxy-middleware,命令:npm install http-proxy-middleware --save
- 创建文件src/setupProxy.js
const { createProxyMiddleware } = require('http-proxy-middleware');module.exports = function(app) {app.use('/api',createProxyMiddleware({target: 'http://localhost:5000',changeOrigin: true,}));
};
setupProxy.js文件举例:
const { createProxyMiddleware } = require('http-proxy-middleware');module.exports = function(app) {app.use('/api',createProxyMiddleware({target: 'http://localhost:8080',// target: 'https://movie.douban.com/',changeOrigin: true}));
};
- 随便找个不需要token的网络接口测试即可,如:豆瓣电影,
https://movie.douban.com/j/search_tags?type=movie&source=index - app.js文件测试:
import logo from './logo.svg';
import './App.css';
import axios from 'axios';
import { useEffect } from 'react';function App() {useEffect(() => {console.log('useEffect');axios.get('/api/test/test/longwang/1').then((res) => {// axios.get('/api/j/search_tags?type=movie&source=index').then((res) => {console.log(res.data);});}, []);return (<div className="App">{/* <header className="App-header"><img src={logo} className="App-logo" alt="logo" /><p>Edit <code>src/App.js</code> and save to reload.</p><aclassName="App-link"href="https://reactjs.org"target="_blank"rel="noopener noreferrer">Learn React</a></header> */}app</div>);
}export default App;
2. 配置路由
- 安裝路由依赖,npm i --save react-router-dom
- 创建三个文件夹,router、components、views,其中router用于指定路由页面,components用于存放非路由页面,views用于存放路由页面。(rfc快捷提示键直接生成函数式组件。
代码举例:
分别是,App.js、router.js - App.js
import logo from './logo.svg';
import './App.css';
import IndexRouter from './router/IndexRouter';function App() {return (<div><IndexRouter></IndexRouter></div>);
}export default App;
- router.js
import React from 'react'
import { HashRouter, Route, Switch } from 'react-router-dom'
import Login from '../views/login/Login'
import NewsSandBox from '../views/sandbox/NewsSandBox'export default function IndexRouter() {return (<HashRouter><Switch><Route path="/login" component={Login}></Route>{/* <Route path="/" component={NewsSandBox}></Route> */}<Route path="/" router={() =>localStorage.getItem('token') ? <NewsSandBox></NewsSandBox> : <Login></Login>}></Route></Switch></HashRouter>)
}