1. 程式人生 > 實用技巧 >React+react-router-dom+redux+axios專案搭建

React+react-router-dom+redux+axios專案搭建

React+react-router-dom+redux+axios專案搭建

一.搭建react專案

1.建立一個react專案

create-react-app my-app

cd my-app

npm start

資料夾目錄結構:

看下頁面是否開啟,是否執行正確。

注意:如果頁面沒有src資料夾,

解除安裝全域性安裝包:

npm uninstall -g create-react-app

yarn global remove create-react-app

然後 npm start,瀏覽器會開啟頁面。

二.搭建react路由

刪除App等檔案,最後目錄結構

1.安裝:react-router-dom

npm install --save react-router-dom

2.新建index頁面

src/Index.js

importReactfrom'react'; importReactDOMfrom'react-dom'; importReactMapfrom'./router/routerMap'; importreportWebVitalsfrom'./reportWebVitals';
ReactDOM.render( <div> <ReactMap/> </div> ,document.getElementById('root'));
//Ifyouwanttostartmeasuringperformanceinyourapp,passafunction //tologresults(forexample:reportWebVitals(console.log)) //orsendtoananalyticsendpoint.Learnmore:https://bit.ly/CRA-vitals reportWebVitals();

3.新建routerMap頁面

src/router/routerMap.js

import React from 'react'
import { HashRouter as Router, Route } from 'react-router-dom'
import Login from '../pages/Login/Login'

class ReactMap extends React.Component {

  updateHandle() {
    console.log("每次router變化後觸發")
  }

  render() {
    return (
      <Router history={this
.props.history}> <Route exact path="" component={Login} /> </Router> ) } } export default ReactMap;

3.新建Login頁面

src/pages/Login/Login.js

import React, { Component } from 'react'

class Login extends Component {
  render() {
    return (
      <div>hello react!</div>
    )
  }
}

export default Login;

目錄結構如下

三.搭建redux

1.安裝 react-redux, redux, redux-thunk

npm install --save react-redux

npm install --save redux

npm install --save redux-thunk

2.修改Index頁面

src/Index.js

import React from 'react';
import ReactDOM from 'react-dom';
import ReactMap from './router/routerMap';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux'
import { createStore, applyMiddleware, compose } from 'redux'
import rootRedux from './redux'
import thunk from 'redux-thunk'
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose
const enhancer = composeEnhancers(applyMiddleware(thunk));
const store = createStore(
  rootRedux,
  enhancer
)
ReactDOM.render(
  <div>
    <Provider store={store}>
      <ReactMap />
    </Provider>
  </div>
  , document.getElementById('root'));
// 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();

3.新建redux/index.js檔案

src/redux/index.js

import { combineReducers } from 'redux'
import set from './set'
export default combineReducers({
  data: set
})

4.新建redux/ set.js檔案

src/redux/set.js,這裡返回的key名:list,是使用時候的key名,不要重複

const set = (state = [], action) => {
  switch (action.type) {
    case 'GET_LIST':
      return {
        ...state,
        list: action.list
      }
    case 'SET_USERNAME':
      return {
        ...state,
        userName: action.list
      }
    default: return state
  }
}

export default set

5.新建actions / index.js檔案

src/actions/index.js

export const getList = (list) => {
  return {
    type: 'GET_LIST',
    list: list
  }
}

export const setUserName = (list) => {
  return {
    type: 'SET_USERNAME',
    list: list
  }
}

6.使用:

//在要使用的頁面裡面引入,這裡獲取了list

import React, { Component } from 'react'
import { connect } from 'react-redux'
import { getList } from '../../actions/index'

class Login extends Component {
  componentDidMount() {
    const { dispatch } = this.props
    //設定引數
    dispatch(getList({ 'back': true, 'user': true, 'homepage': true }))
    //獲取引數
    const list = this.props.data.list
    console.log(list)
  }

  render() {
    return (
      <div>hello react!</div>
    )
  }
}

export default connect(state => state)(Login);

目錄結構:

四.不抽離 webpack配置的方案antd(npm run build 後找不到圖片路徑,暫未解決)

cnpm install --save react-app-rewired customize-cra

cnpm install --save babel-plugin-import

1.配置less,less-loader

cnpm install --save less less-loader

2. 根目錄新建config-overrides.js檔案

const { override, fixBabelImports, addWebpackAlias, addLessLoader } = require('customize-cra')
const path = require('path')
function resolve(dir) {
  return path.join(__dirname, dir)
}

// addLessLoader 新增less的引用
// fixBabelImports 按需載入antd元件
// addWebpackAlias 路徑別名配置
/* 路徑別名配置 */
module.exports = override(
  addWebpackAlias({
    '@': resolve('src'),
    components: resolve('./src/components'),
    assets: resolve('./src/assets'),
    static: resolve('./src/static'),
    img: resolve('./src/static/img'),
    js: resolve('./src/static/js'),
    css: resolve('./src/static/css'),
  }),
  /* antd元件按需載入 */
  fixBabelImports('import', {
    libraryName: 'antd',
    libraryDirectory: 'es',
    style: true,
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: { '@primary-color': '#1DA57A' },
  }),

);

3. 修改package.json檔案,目錄結構

4. 使用:頁面引用less

import'@/static/css/index.less'

五.抽離 webpack配置的方案

npm run eject

執行後會出現config資料夾,在裡面配置less 和路徑別名配置

1.配置less,less-loader

cnpm install --save less less-loader

在webpack.config.js裡面進行less的配置

2.配置路徑別名

在webpack.config.js裡面進行路徑別名的配置

六.配置server, axios

1.配置antd,axios

//安裝antd 元件庫

npm install –save antd

//安裝axios

npm install –save axios

2.src路徑下新建server資料夾,新建server.js檔案

import axios from 'axios'
//引入antd外掛
import { message } from 'antd'

// ip地址
axios.defaults.baseURL = 'http://127.0.0.1:8081'
axios.defaults.timeout = 300000

// 新增請求攔截器 
axios.interceptors.request.use(function (config) {
  // 在傳送請求之前做些什麼
  return config;
}, function (error) {
  // 對請求錯誤做些什麼
  return Promise.reject(error);
});

// 新增響應攔截器
axios.interceptors.response.use(function (response) {
  // 對響應資料做點什麼
  const data = response.data
  if (!data.success) {
    // message.error(data.msg)
  }
  return data;
}, function (error) {
  // 對響應錯誤做點什麼
  message.error('伺服器錯誤')
  return Promise.reject(error);
});

// 登入介面
export let checkPatientLogin = async (obj) => {
  return await axios.post('/checkPatientLogin', obj)
}

3.使用:頁面引用

import{checkPatientLogin}from'@/server/server'

六.打包

1.修改package.json檔案

2.npm run build

成功後會出現build資料夾,雙擊index.html在瀏覽器開啟,可以正常執行