02-HK租房 从0 到 1
本文是 hkzf 移动端 的系列教程,旨在通过一系列的文章来帮助初学者快速掌握基于React技术栈的项目开发。
路由配置
基本知识点
例子
import React from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
export default function BasicExample() {
return (
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/dashboard">Dashboard</Link>
</li>
</ul>
<hr />
{/*
A <Switch> looks through all its children <Route>
elements and renders the first one whose path
matches the current URL. Use a <Switch> any time
you have multiple routes, but you want only one
of them to render at a time
*/}
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/about">
<About />
</Route>
<Route path="/dashboard">
<Dashboard />
</Route>
</Switch>
</div>
</Router>
);
}
// You can think of these components as "pages"
// in your app.
function Home() {
return (
<div>
<h2>Home</h2>
</div>
);
}
function About() {
return (
<div>
<h2>About</h2>
</div>
);
}
function Dashboard() {
return (
<div>
<h2>Dashboard</h2>
</div>
);
}
两种路由方式
import { BrowserRouter,HashRouter } from "react-router-dom"
- HashRouter
- BrowserRouter
两者的区别在与路由显示方式不同:
HashRouter => https://bnpsd.csb.app/#/about
BrowserRouter => https://bnpsd.csb.app/about
三种渲染方式
在react-router的中,有3种渲染方式
- component 每次渲染都会触发组件的对应的生命周期
- render 内联模式渲染 props需要传递到函数内
- children 一直渲染 props需要传递到函数内
<Route path="/home" component={Home} />
<Route path="/home" render={(props) => <Home {...props} />}/>
<Route path="/home" children={() => <About/>}/>
HK项目中的路由配置
在HK项目src/App.js文件中,可以找到对应的路由信息,采用的是children的渲染模式,为每一个配置的route
添加了关键字exact
,精准匹配每一个路由。
import React,{ Fragment } from "react"
import { HashRouter as Router,Route} from "react-router-dom"
import Home from "./pages/Home"
import List from "./pages/List"
import News from "./pages/News"
import Profile from "./pages/Profile"
import HKLayout from "./components/HKLayout"
import { getCityNameAction } from './store/actionCreator'
import BMap from './pages/BMap'
import CityList from './pages/CityList'
import store from "./store"
export default class TabBarExample extends React.Component {
componentDidMount(){
this.getLocalCity();
}
getLocalCity = (params) => {
let map = new window.BMap.LocalCity();
map.get((result) => {
const cityName = "广州" || result.name;
store.dispatch(getCityNameAction(cityName));
}
)
}
render(){
return <Fragment>
<Router>
<Route path="/" exact render={()=> <HKLayout><Home/></HKLayout>}></Route>
<Route path="/List" exact render={()=><HKLayout> <List/></HKLayout>}></Route>
<Route path="/News" exact render={()=><HKLayout><News/></HKLayout>}></Route>
<Route path="/Profile" exact render={()=><HKLayout><Profile/></HKLayout>}></Route>
<Route path="/CityList" exact component={CityList}></Route>
<Route path="/BMap" exact component={BMap}></Route>
</Router>
</Fragment>
}
}
环境变量配置
基本知识点
.env
文件在由 creact-react-app 生成的项目里是一个关于当环境的配置文件,
我们可以在这个文件里写一些配置,在实际开发中,我们会有开发、staging、生产等环境,每个环境的配置都不尽相同,最基本地,每个环境请求的后端服务器的 url 就不相同,自己 mock 的时候的本机地址、与后端联调时候的局域网的地址,staging 的域名和正式上线环境的域名等等。
下面是对应的.env文件的应用,.env一般是放置在项目根目录下:
-
.env
: 默认 -
.env.local
: 本地变量 这个文件是除了test之外会应用到的环境 -
.env.development
,.env.test
,.env.production
: Environment-specific settings 环境特定的变量. -
.env.development.local
,.env.test.local
,.env.production.local
: 覆盖本地特定的环境变量
左边的文件比右边的有更多优先权:
-
npm start
:.env.development.local
,.env.development
,.env.local
,.env
-
npm run build
:.env.production.local
,.env.production
,.env.local
,.env
-
npm test
:.env.test.local
,.env.test
,.env
(note.env.local
is missing)
在HK项目中,我们配置了两个配置文件 .env.development
(用于开发环境)和.env.production
(用于生产环境)
.env.development
REACT_APP_API_URL = http://hkzf.zbztb.cn
.env.production
REACT_APP_API_URL = http://hkzf.zbztb.xxx
在项目中使用 REACT_APP_API_URL
/**
* 通用的接口url
*/
export let REACT_APP_API_URL = process.env.REACT_APP_API_URL
请求拦截器
默认配置
你指定的默认配置将会被应用到每个请求中
全局的axios配置
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
自定义的默认实例
// Set config defaults when creating the instance
const instance = axios.create({
baseURL: 'https://api.example.com'
});
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;
配置的优先顺序
配置将会以以下的优先顺序被合并。默认配置在lib/defaults.js里面可以找到。然后是实例的 defaults
属性,之后就是请求的config
参数。后者将会比前者优先权更高。下面是一个例子。
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
const instance = axios.create();
// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;
// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
timeout: 5000
});
Interceptors
你可以在请求或者响应被拦截前使用 then
或者catch
// Add a request interceptor
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) {
// Any status code that lie within the range of 2xx cause this function to trigger
// Do something with response data
return response;
}, function (error) {
// Any status codes that falls outside the range of 2xx cause this function to trigger
// Do something with response error
return Promise.reject(error);
});
如果你想移除一个拦截器你可以
const myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
你可以添加一个拦截器到一个自定义的axios实例中。
const instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});
在HK项目中配置axios
src/utils/request.js
import Axios from "axios"
import { Toast } from "antd-mobile"
import { REACT_APP_API_URL } from "./urls"
//1. 配置一个通用的url
export let axios = Axios.create({
baseURL:REACT_APP_API_URL
})
//2. 请求拦截
axios.interceptors.request.use(function(config){
Toast.loading("正在加载中...",1*60*60,null,true);
return config;
},function(error){
return Promise.reject(error)
})
//3. 返回数据的拦截
axios.interceptors.response.use(function( res ){
Toast.hide();
return res.data;
},
function(error){
return Promise.reject(error);
})