02-HK租房 从0 到 1

简介: 本文是 hkzf 移动端 的系列教程,旨在通过一系列的文章来帮助初学者快速掌握基于React技术栈的项目开发。

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"
  1. HashRouter
  2. 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配置

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);
})
目录
相关文章
|
11月前
.club九周年,相聚于此尽享钜惠
.club域名旨在促进和培养各种各样的人际关系,电玩、盲盒、音乐、体育、汽车……这是一个适用于任何兴趣或事业的域名。
|
智能硬件
JD+ 智能奶茶馆开业,刘强东打的什么算盘?
总理前天刚在创业大街喝了杯咖啡,昨天东哥奶茶馆的芳香就紧随而至。 京东旗下 JD+ 智能奶茶馆昨天正式开门迎客。JD+ 是京东去年开始就在着力打造的智能硬件创业生态。来到第二季的 JD+ 的剧情更显波澜壮阔。京东开始从单纯卖硬件朝搭建全产业链过渡。孵化、加速新创企业,整合产业链,建立全平台,京东智能战略野心十足。作为深度布局的标志性一步,JD+ 智能奶茶馆将在线下扮演重要角色。
197 0
JD+ 智能奶茶馆开业,刘强东打的什么算盘?
|
前端开发 开发工具 git
01-HK租房 从0 到 1
本系列是基于React技术栈做的一个移动端租房应用,可作为一个初学React者的入门教程
1044 0
【阿里云ACE 北京】[AA 羽毛球休闲] 3月11日 大兴体育局羽毛球馆
前言介绍:阿里云 ACE(Alibaba Cloud Engineer) 同城会于2017年11月成立, 首批参与者自发命名这个组织为ACE,寓意是每个人都是阿里云的建设者、阿里云的工程师。 Ace又是扑克牌中的“A",寓意这个群体是阿里云生态中最王牌的一群人。
1986 0
|
云栖大会
2017杭州云栖大会,你带走.club的猴米米了吗?
2017杭州云栖大会于2017年10月11日盛大开幕,会场火爆程度可以说是史无前例。.CLUB展位别具一格,颇有创意,在这次云栖大会上赚足眼光。
2917 0

热门文章

最新文章