總結了點React,咱也不敢說

React總結

1. 搭環境

此處默認各位都是有那麼一點前端開發經驗的,因此Node自行安裝。html

1.1 腳手架

  • 官方推薦 => create-react-app
// install
$ npm install -g create-react-app
複製代碼

1.2 起項目

1.2.1 package.json

// setting
"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
}
複製代碼

1.2.2 start

// start
$ npm run start
複製代碼

1.2.3 打包

// start
$ npm run build
複製代碼

2. 項目結構

|public
|----|favicon.ico
|----|index.html
|dist
|src 
|----|common
|    |pages
|    |statics
|    |----|img
|    |    |iconfont
|    |store
|    |----|index.js
|    |    |reducer.js
|    |    |actionTypes.js
|    |    |actionCreators.js
|    |App.js
|    |index.js
|package.json
|README.md
複製代碼

3. 入口文件

  • /src/index前端

  • 指定渲染的文件以及渲染的文件插入的DOM節點(document.getElementById('root'))。react

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root')); 複製代碼

4. 渲染的入口文件

  • /src/App.jsios

  • 路由/全局樣式/派發store……npm

import React, { Component } from 'react';
import { GlobalStyle, RouteStyle } from "./style";
import { FontGlobal } from "./statics/iconfont/iconfont";
import { Provider } from "react-redux";
import { BrowserRouter, Route } from "react-router-dom";
import Home from "./pages/home";
import Detail from "./pages/detail";
import store from "./store"

class App extends Component {
  render() {
    const providerStyle = {
      width: "100%",
      height: "100%"
    };
    return (
      <Provider store={store}>
        <div style={providerStyle}>
          <GlobalStyle />
          <FontGlobal />
          <BrowserRouter>
            <RouteStyle>
              <Route path="/" exact component={Home} />
              <Route path="/detail" exact component={Detail} />
            </RouteStyle>
          </BrowserRouter>
        </div>
      </Provider>
    );
  }
}

export default App;
複製代碼

4.1 路由

  • 依賴包 => react-router-dom

4.1.1 install

$ npm i react-router-dom -S
複製代碼

4.1.2 路由表

import { BrowserRouter, Route } from "react-router-dom";

<BrowserRouter>
  <Route path="/" exact component={Home} />
  <Route path="/detail" exact component={Detail} />
</BrowserRouter>
複製代碼
  • exact精確匹配path路徑。json

  • component表示當前路徑加載組件。redux

4.1.3 路由傳參

4.1.3.1 通配符
  • 刷新頁面參數不會丟失,但很醜
// Route
<Route path='/path/:name' component={}/>

// Link組件
<Link to="/path/xxx"></Link>

// 取參
this.props.match.params.name
複製代碼
4.1.3.2 query
  • 好看但會丟失參數
// Route
<Route path='/path' component={}/>

// Link組件
<Link to="{{ pathname: "/path", query: "queryValue" }}></Link> // 取參 this.props.location.query 複製代碼
4.1.3.3 state
  • 同query
// Route
<Route path='/path' component={}/>

// Link組件
<Link to="{{ pathname: "/path", state: "stateValue" }}></Link> // 取參 this.props.location.state 複製代碼

4.1.4 路由跳轉

4.1.4.1 Link
<Line to="/path"></Link>
複製代碼
4.1.4.2 history.push
this.props.history.push({ pathname:' /user', ……})
複製代碼

4.2 樣式

  • 依賴包 => styled-componentsaxios

  • 將頁面中的標籤等用js封裝成樣式的組件。api

4.2.1 全局樣式

// 1. 導出GlobalStyle
import styled, { createGlobalStyle } from "styled-components";

export const GlobalStyle = createGlobalStyle`
html {
  width: 100%;
  height: 100%;
}
`;

// 2. 在渲染入口文件中添加
<Provider>
  <div style={providerStyle}>
    <GlobalStyle />
    <FontGlobal />
    <BrowserRouter>
      <RouteStyle>
        <Route path="/" exact component={Home} />
        <Route path="/detail" exact component={Detail} />
      </RouteStyle>
    </BrowserRouter>
  </div>
</Provider>
複製代碼

4.2.2 局部樣式

import styled from "styled-components";

export const Img = styled.img.attrs({
  src: xxx
})` width: 100px; height: 100px; `;

// 導入使用
<Img/>
複製代碼

4.3 派發store

import { Provicer } from "react-redux";
import store from "./store"

<Provicer store={store}>
  // 組件內都能接收到store
</Provicer>
複製代碼

4.3.1 組件內接收

import { connect } "react-redux";

class Header extends Component {
  render() {
    return (
      <div onClick={this.props.handleDispach}>Hello</div>
      this.props.login
        ? <div>Logout</div>
        : <div>Login</div>
    )
  }
}

const mapStateToProps = (state) => ({
  // 映射store裏面的值
  login: state.get("login")
});

const mapDispatchToProps = (dispatch) => {
  return {
    // 接受掛載在props上的方法  
    handleDispach() {
      // TODO
      dispatch(action);
    }
  }
};

export default connect(mapStateToProps, mapDispatchToProps)(Heacer);
複製代碼

5. redux

  • 依賴包 => redux/react-redux/redux-thunk/immutable/redux-immutable

5.1 redux

  • 用於構建store實例
import { createStore ,applyMiddleware, compose } from "redux";
import reducer from "./reducer";
import thunk from "redux-thunk";

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
  reducer,
  composeEnhancers(applyMiddleware(thunk))
);

export default store;
複製代碼

5.2 react-redux

  • 用於派發store,在頁面中映射state數據等。bash

  • 如上4.3.

5.3 redux-thunk

  • 同過redux的中間件使用thunk。

  • 用於在actionCreator.js中返回一個函數。

  • 異步數據的處理。

// 1. 普通數據
export const handleSwitchList = (value) => ({
  type: actionTypes.SWITCH_LIST,
  value
});

// 2. 異步數據 =》 提供dispatch方法將action傳給頁面供用戶調用。
// mapDispatchToProps(dispatch)會派發action。
export const handleRecommendList = () => {
  return (dispatch) => {
    axios.get("/api/recommendList.json").then(res => {
      res = res.data.data;
      dispatch(handleRecomList(res));
    }).catch(err => {
      throw Error(err);
    })
  }
};
複製代碼

5.4 immutable

  • 用於將數據結構變成immutable形式,強制修改會報錯。
// reducer.js
import { fromJS } from "immutable";

const defaultState = fromJS({
  value: xxxx
}) 

export default (state, action) => {
  if (action.type ==="xxx") {
    return state.set("value", state.get("value"));
  }
}
複製代碼

5.5 redux-immutable

  • 用於將多個reducer合併。
import { combineReducers } from "redux-immutable";
import { reducer as headerReducer } from "../common/header/store";
import { reducer as homeReducer } from "../pages/home/store";
import { reducer as loginReducer} from "../pages/login/store";

export default combineReducers({
  header: headerReducer,
  home: homeReducer,
  login: loginReducer
})
複製代碼

6. 動畫

  • 依賴包 => react-transition-group

  • 具體上GitHub

7. 生命週期函數

相關文章
相關標籤/搜索