使用create-react-app+react-router-dom+axios+antd+react-redux构建react项目_蜡烛_前端开发者

1、安装、构建

# 全局安装
npm install -g create-react-app
# 构建一个my-app的项目
npx create-react-app my-app
cd my-app

# 启动编译当前的React项目,并自动打开 http://localhost:3000/
npm start
# 全局安装
npm install -g create-react-app
# 构建一个my-app的项目
npx create-react-app my-app
cd my-app

# 启动编译当前的React项目,并自动打开 http://localhost:3000/
npm start

# 全局安装
npm install
app
# 构建一个my
app的项目
npx create
app
cd my
app

# 启动编译当前的React项目,并自动打开 http://localhost:3000/

2、项目目录

//默认

├── package.json ├── public # 这个是webpack的配置的静态目录 │ ├── favicon.ico │ ├── index.html # 默认是单页面应用,这个是最终的html的基础模板 │ └── manifest.json ├── src │ ├── App.css # App根组件的css │ ├── App.js # App组件代码 │ ├── App.test.js │ ├── index.css # 启动文件样式 │ ├── index.js # 启动的文件(开始执行的入口)!!!! │ ├── logo.svg │ └── serviceWorker.js └── yarn.lock
//默认

├── package.json ├── public # 这个是webpack的配置的静态目录 │ ├── favicon.ico │ ├── index.html # 默认是单页面应用,这个是最终的html的基础模板 │ └── manifest.json ├── src │ ├── App.css # App根组件的css │ ├── App.js # App组件代码 │ ├── App.test.js │ ├── index.css # 启动文件样式 │ ├── index.js # 启动的文件(开始执行的入口)!!!! │ ├── logo.svg │ └── serviceWorker.js └── yarn.lock

//默认

├── package.json
├── public # 这个是webpack的配置的静态目录
│ ├── favicon.ico
│ ├── index.html # 默认是单页面应用,这个是最终的html的基础模板
│ └── manifest.json
├── src
│ ├── App.css # App根组件的css
│ ├── App.js # App组件代码
│ ├── App.test.js
│ ├── index.css # 启动文件样式
│ ├── index.js # 启动的文件(开始执行的入口)!!!!
│ ├── logo.svg
│ └── serviceWorker.js
└── yarn.lock

//修改
├── package.json
├── public                  # 这个是webpack的配置的静态目录
│   ├── favicon.ico
│   ├── index.html          # 默认是单页面应用,这个是最终的html的基础模板
│   └── manifest.json
├── src
│   ├── assets            # 图片等静态资源
│   ├── redux             # 状态
│   │      ├── action.js                 # action
│   │      ├──reducerjs              # reducer
│   │      └── index.js                 # 主文件
│   ├── router             # 路由
│   │      ├── config.js                 # 配置
│   │      ├── FrontendAuth.js      # 路由守卫
│   │      └── index.js                 # 主文件
│   ├── serve            # 请求
│   │      ├── index.js            # axio
│   ├── views            # 页面
│   ├── App.css             # App根组件的css
│   ├── App.js              # App组件代码
│   ├── App.test.js
│   ├── index.css           # 启动文件样式
│   ├── index.js            # 启动的文件(开始执行的入口)!!!!
│   ├── logo.svg
│   └── serviceWorker.js
└── yarn.lock          
//修改
├── package.json
├── public                  # 这个是webpack的配置的静态目录
│   ├── favicon.ico
│   ├── index.html          # 默认是单页面应用,这个是最终的html的基础模板
│   └── manifest.json
├── src
│   ├── assets            # 图片等静态资源
│   ├── redux             # 状态
│   │      ├── action.js                 # action
│   │      ├──reducerjs              # reducer
│   │      └── index.js                 # 主文件
│   ├── router             # 路由
│   │      ├── config.js                 # 配置
│   │      ├── FrontendAuth.js      # 路由守卫
│   │      └── index.js                 # 主文件
│   ├── serve            # 请求
│   │      ├── index.js            # axio
│   ├── views            # 页面
│   ├── App.css             # App根组件的css
│   ├── App.js              # App组件代码
│   ├── App.test.js
│   ├── index.css           # 启动文件样式
│   ├── index.js            # 启动的文件(开始执行的入口)!!!!
│   ├── logo.svg
│   └── serviceWorker.js
└── yarn.lock          

//修改├── package.json
├── public # 这个是webpack的配置的静态目录
│ ├── favicon.ico
│ ├── index.html # 默认是单页面应用,这个是最终的html的基础模板
│ └── manifest.json
├── src
│ ├── assets # 图片等静态资源
│ ├── redux # 状态
│ │ ├── action.js # action
│ │ ├──reducerjs # reducer
│ │ └── index.js # 主文件
│ ├── router # 路由
│ │ ├── config.js # 配置
│ │ ├── FrontendAuth.js # 路由守卫
│ │ └── index.js # 主文件
│ ├── serve # 请求
│ │ ├── index.js # axio
│ ├── views # 页面
│ ├── App.css # App根组件的css
│ ├── App.js # App组件代码
│ ├── App.test.js
│ ├── index.css # 启动文件样式
│ ├── index.js # 启动的文件(开始执行的入口)!!!!
│ ├── logo.svg
│ └── serviceWorker.js
└── yarn.lock

 

3、antd

yarn add antd
yarn add antd

修改 src/App.css,在文件顶部引入 antd/dist/antd.css

src/App.cssantd/dist/antd.css

@import '~antd/dist/antd.css';

.App {
  text-align: center;
}

...
@import '~antd/dist/antd.css';

.App {
  text-align: center;
}

...

;

.App {
textalign: center;
}

antd 目前的默认文案是英文,如果需要使用其他语言,可以参考下面的方案。

antd

antd 提供了一个 React 组件 ConfigProvider 用于全局配置国际化文案。

ConfigProvider

import zhCN from 'antd/es/locale/zh_CN';

return (
  <ConfigProvider locale={zhCN}>
    <App />
  </ConfigProvider>
);
import zhCN from 'antd/es/locale/zh_CN';

return (
  <ConfigProvider locale={zhCN}>
    <App />
  </ConfigProvider>
);

;

return (

4、axios

yarn add axios
yarn add axios

/src/serve/index.js,统一配置并绑定到react上

import React from 'react';
import axios from 'axios';
axios.defaults.headers['Content-Type'] = 'application/json';


let config = {
  baseURL: '',
  timeout: 60 * 1000, // Timeout
};
const _axios = axios.create(config);
_axios.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    config.headers['Authorization'] = '';
    return config;
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  (response) => {
    // Do something with response data
    return response
  },
  (error) => {
    // Do something with response error
    return Promise.reject();
  }
);
React.Component.prototype.$axios = _axios;
import React from 'react';
import axios from 'axios';
axios.defaults.headers['Content-Type'] = 'application/json';


let config = {
  baseURL: '',
  timeout: 60 * 1000, // Timeout
};
const _axios = axios.create(config);
_axios.interceptors.request.use(
  (config) => {
    // Do something before request is sent
    config.headers['Authorization'] = '';
    return config;
  },
  (error) => {
    // Do something with request error
    return Promise.reject(error);
  }
);

// Add a response interceptor
_axios.interceptors.response.use(
  (response) => {
    // Do something with response data
    return response
  },
  (error) => {
    // Do something with response error
    return Promise.reject();
  }
);
React.Component.prototype.$axios = _axios;

;
import axios from
;
axios.defaults.headers[
;

let config {
baseURL:
,
timeout:
// Timeout};
const _axios
axios.create(config);
_axios.interceptors.request.use(
(config)
{
// Do something before request is sent;
return config;
},
(error)
{
// Do something with request errorreturn Promise.reject(error);
}
);

// Add a response interceptor_axios.interceptors.response.use(
(response)
{
// Do something with response datareturn response
},
(error)
{
// Do something with response errorreturn Promise.reject();
}
);
React.Component.prototype.$axios

5、router

yarn add react-router-dom
yarn add react-router-dom

/src/router/config.js

import login from '../views/login';
import record from '../views/record';
import home from '../views/home';


export const routerConfig = [
  {
    path:'/',
    component:home,
    auth:true,
  },{
    path:'/record',
    component:record,
    //auth:true,
  },{
    path:'/login',
    component:login,
  }
];
import login from '../views/login';
import record from '../views/record';
import home from '../views/home';


export const routerConfig = [
  {
    path:'/',
    component:home,
    auth:true,
  },{
    path:'/record',
    component:record,
    //auth:true,
  },{
    path:'/login',
    component:login,
  }
];

;
import record from
;
import home from
;

export const routerConfig [
{
path:
,
component:home,
auth:
true,
},{
path:
,
component:record,
//auth:true, },{
path:
,
component:login,
}
];

/src/router/FrontendAuth.js

import React, {Component} from 'react';
import {Route, Redirect} from 'react-router-dom';

export class FrontendAuth extends Component {
  render() {
    const {location, config} = this.props;
    const {pathname} = location;
    const isLogin = localStorage.getItem('__config_center_token')

    // 如果该路由不用进行权限校验,登录状态下登陆页除外
    // 因为登陆后,无法跳转到登陆页
    // 这部分代码,是为了在非登陆状态下,访问不需要权限校验的路由
    const targetRouterConfig = config.find((v) => v.path === pathname);
    if (targetRouterConfig && !targetRouterConfig.auth && !isLogin) {
      const {component} = targetRouterConfig;
      return <Route exact path={pathname} component={component}/>
    }

    if (isLogin) {
      // 如果是登陆状态,想要跳转到登陆,重定向到主页
      if (pathname === '/login') {
        return <Redirect to='/'/>
      } else {
        // 如果路由合法,就跳转到相应的路由
        if (targetRouterConfig) {
          return <Route path={pathname} component={targetRouterConfig.component}/>
        } else {
          // 如果路由不合法,重定向到 404 页面
          return <Redirect to='/404'/>
        }
      }
    } else {
      // 非登陆状态下,当路由合法时且需要权限校验时,跳转到登陆页面,要求登陆
      if (targetRouterConfig && targetRouterConfig.auth) {
        return <Redirect to='/login'/>
      } else {
        // 非登陆状态下,路由不合法时,重定向至 404
        return <Redirect to='/404'/>
      }
    }
  }
}
import React, {Component} from 'react';
import {Route, Redirect} from 'react-router-dom';

export class FrontendAuth extends Component {
  render() {
    const {location, config} = this.props;
    const {pathname} = location;
    const isLogin = localStorage.getItem('__config_center_token')

    // 如果该路由不用进行权限校验,登录状态下登陆页除外
    // 因为登陆后,无法跳转到登陆页
    // 这部分代码,是为了在非登陆状态下,访问不需要权限校验的路由
    const targetRouterConfig = config.find((v) => v.path === pathname);
    if (targetRouterConfig && !targetRouterConfig.auth && !isLogin) {
      const {component} = targetRouterConfig;
      return <Route exact path={pathname} component={component}/>
    }

    if (isLogin) {
      // 如果是登陆状态,想要跳转到登陆,重定向到主页
      if (pathname === '/login') {
        return <Redirect to='/'/>
      } else {
        // 如果路由合法,就跳转到相应的路由
        if (targetRouterConfig) {
          return <Route path={pathname} component={targetRouterConfig.component}/>
        } else {
          // 如果路由不合法,重定向到 404 页面
          return <Redirect to='/404'/>
        }
      }
    } else {
      // 非登陆状态下,当路由合法时且需要权限校验时,跳转到登陆页面,要求登陆
      if (targetRouterConfig && targetRouterConfig.auth) {
        return <Redirect to='/login'/>
      } else {
        // 非登陆状态下,路由不合法时,重定向至 404
        return <Redirect to='/404'/>
      }
    }
  }
}

;
import {Route, Redirect} from
;

export class FrontendAuth extends Component {
render() {
const {location, config} this.props;
const {pathname}
location;
const isLogin
)

// 如果该路由不用进行权限校验,登录状态下登陆页除外// 因为登陆后,无法跳转到登陆页// 这部分代码,是为了在非登陆状态下,访问不需要权限校验的路由 pathname);
ifisLogin) {
const {component}
targetRouterConfig;
return }

if (isLogin) {
// 如果是登陆状态,想要跳转到登陆,重定向到主页if) {
returnelse {
// 如果路由合法,就跳转到相应的路由if (targetRouterConfig) {
returnelse {
// 如果路由不合法,重定向到 404 页面return }
}
}
else {
// 非登陆状态下,当路由合法时且需要权限校验时,跳转到登陆页面,要求登陆if targetRouterConfig.auth) {
returnelse {
// 非登陆状态下,路由不合法时,重定向至 404return }
}
}
}

/src/router/index.js

import React, { Component } from 'react';
import { Switch} from 'react-router-dom';

import { FrontendAuth } from './FrontendAuth';
import { routerConfig } from './config';


class Routes extends Component {
  render() {
    return (
      <Switch>
        <FrontendAuth config={routerConfig} />
      </Switch>
    )
  }
}

export default Routes
import React, { Component } from 'react';
import { Switch} from 'react-router-dom';

import { FrontendAuth } from './FrontendAuth';
import { routerConfig } from './config';


class Routes extends Component {
  render() {
    return (
      <Switch>
        <FrontendAuth config={routerConfig} />
      </Switch>
    )
  }
}

export default Routes

;
import { Switch} from
;

import { FrontendAuth } from ;
import { routerConfig } from
;

class Routes extends Component {
render() {
return (
)
}
}

export default

app.js

import {BrowserRouter as Router} from 'react-router-dom';
import Routes from './router/index'

class App extends Component  {
  render() {
    return (
      <Router>
        <Routes></Routes>
      </Router>
    );
  }
}

export default App;
import {BrowserRouter as Router} from 'react-router-dom';
import Routes from './router/index'


class App extends Component  {
  render() {
    return (
      <Router>
        <Routes></Routes>
      </Router>
    );
  }
}

export default App;


class App extends Component {
render() {
return (
<Router>
<Routes></Routes>
</Router>
);
}
}

export default App;
class App extends Component {
render() {
return (
);
}
}

export default

6、scss

 安装完后,只要把sass文件改成.scss就行了

npm install node-sass sass-loader --save
npm install node-sass sass-loader --save

7、修改端口号

项目默认端口号是3000,如下可以更改:

在package.json中修改
  "start":"react-scripts start",
为
"start":"set PORT=9000 && react-scripts start",
在package.json中修改
  "start":"react-scripts start",
为
"start":"set PORT=9000 && react-scripts start",

在package.json中修改
,

8、react-redux

redux不是项目必需的,如果你不确定是否需要,那就是不需要,在react无法实现时,再考虑。

npm install react-redux redux --S
npm install react-redux redux --S

 /src/redux/action.js

/*
 * action 类型
 */

export const COUNT = 'COUNT';
/*
 * 初始值
 */

export const config = {
    count:1000
};


/*
 * action 创建函数
 */

export function setCount(value) {
    return { type: COUNT, value }
}
/*
 * action 类型
 */

export const COUNT = 'COUNT';
/*
 * 初始值
 */

export const config = {
    count:1000
};


/*
 * action 创建函数
 */

export function setCount(value) {
    return { type: COUNT, value }
}

/*
* action 类型
*/

export const COUNT ;
/*
* 初始值
*/

export const config {
count:

};

/*
* action 创建函数
*/

export function setCount(value) {
return { type: COUNT, value }
}

/src/redux/reducer.js

//这是action
import {
  COUNT
} from './actions'

//这是reducer
const reducer = (state , action) => {
  switch (action.type) {
    case COUNT:
      let count =  action.value;
      return {...state,...{count}};
    default:
      return state;
  }
};
export default reducer
//这是action
import {
  COUNT
} from './actions'

//这是reducer
const reducer = (state , action) => {
  switch (action.type) {
    case COUNT:
      let count =  action.value;
      return {...state,...{count}};
    default:
      return state;
  }
};
export default reducer

//这是actionimport {
COUNT
} from
//这是reducer {
switch (action.type) {
case COUNT:
let count
action.value;
return {…state,…{count}};
default:
return state;
}
};
export
default

/src/redux/index.js

import { createStore } from 'redux';
import {config} from './actions';
import reducer from './reducer';
let store = createStore(reducer,config);

export default store
import { createStore } from 'redux';
import {config} from './actions';
import reducer from './reducer';
let store = createStore(reducer,config);

export default store

;
import {config} from
;
import reducer from
;
let store
createStore(reducer,config);

export default

/src/index.js

import { Provider } from 'react-redux'
import store from './redux/index'

ReactDOM.render(
  <ConfigProvider locale={zhCN}>
    <Provider store={store}>
      <App />
    </Provider>
  </ConfigProvider>, document.getElementById('root'));
import { Provider } from 'react-redux'
import store from './redux/index'

ReactDOM.render(
  <ConfigProvider locale={zhCN}>
    <Provider store={store}>
      <App />
    </Provider>
  </ConfigProvider>, document.getElementById('root'));


import store from

ReactDOM.render(

//页面调用示例

import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
  setCount,
} from '../redux/actions'

class ReduxTest extends Component {

  componentDidMount() {
    console.log(this.props)
  }
  render() {
    const { PayIncrease,tiger } = this.props;
    return (
      <div className="App">
        <h2>当月工资为{tiger}</h2>
        <button onClick={PayIncrease}>升职加薪</button>
      </div>
    );
  }
}
//需要渲染什么数据
function mapStateToProps(state) {
  return {
    tiger: state.count
  }
}
//需要触发什么行为
function mapDispatchToProps(dispatch) {
  return {
    PayIncrease: () => dispatch(setCount(99999)),
  }
}

export default ReduxTest = connect(mapStateToProps, mapDispatchToProps)(ReduxTest)
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
  setCount,
} from '../redux/actions'

class ReduxTest extends Component {

  componentDidMount() {
    console.log(this.props)
  }
  render() {
    const { PayIncrease,tiger } = this.props;
    return (
      <div className="App">
        <h2>当月工资为{tiger}</h2>
        <button onClick={PayIncrease}>升职加薪</button>
      </div>
    );
  }
}
//需要渲染什么数据
function mapStateToProps(state) {
  return {
    tiger: state.count
  }
}
//需要触发什么行为
function mapDispatchToProps(dispatch) {
  return {
    PayIncrease: () => dispatch(setCount(99999)),
  }
}

export default ReduxTest = connect(mapStateToProps, mapDispatchToProps)(ReduxTest)

;
import { connect } from
;
import {
setCount,
} from

class ReduxTest extends Component {

componentDidMount() {
console.log(this.props)
}
render() {
const { PayIncrease,tiger }
this.props;
return (
);
}
}
//需要渲染什么数据function mapStateToProps(state) {
return {
tiger: state.count
}
}
//需要触发什么行为function mapDispatchToProps(dispatch) {
return {
PayIncrease: ()
)),
}
}

export default

 

» 本文来自:前端开发者 » 《使用create-react-app+react-router-dom+axios+antd+react-redux构建react项目_蜡烛_前端开发者》
» 本文链接地址:https://www.rokub.com/73581.html
» 您也可以订阅本站:https://www.rokub.com
赞(0)
64K

评论 抢沙发

评论前必须登录!