umi 部分使用介紹


1. 創建頁面及路由

umi  g page index
// 創建index首頁,會創建一個pages文件夾,里面有index.js 和index.css

umi dev
// 啟動項目到8000端口,localhost:8000會顯示剛剛創建的index

umi g page about 
// 創建about頁面, pages文件夾里面增加about.js 和 about.css,即可訪問localhost:8000/about

2. 動態路由添加

 pages文件夾里面創建users文件夾,users文件夾里面創建$id.js和$id.css

// $id.js
import styles from './$id.css';

export default function(props) {
  return (
    <div className={styles.normal}>
      <h1>Page {props.match.params.id} test</h1>
    </div>
  );
}

// url輸入localhost:8000/users/1 顯示 page 1 test
// url輸入localhost:8000/users/2 顯示 page 2 test

umi g page users/_layout
// 在users文件夾里面增加_layout.js 和 _layout.css

// url輸入localhost:8000/users/1 顯示 page layout
// url輸入localhost:8000/users/2 顯示 page layout

// 修改layout.js代碼
import styles from './_layout.css';

export default function(props) {
  return (
    <div className={styles.normal}>
      <h1>Page _layout</h1>
      {props.children} // 顯示子路由內容
    </div>
  );
}

// url輸入localhost:8000/users/1 顯示 page layout 和page 1 test

// url輸入localhost:8000/users/1 顯示 page layout 和page 2 test

3. 動態路由跳轉

umi g page users/index

// users/index 代碼
import Link from 'umi/link'
// umi 對props.history進行了封裝
import router from 'umi/router'
import styles from './index.css';
const users = [
  {id: 1, name: 'Tom'},
  {id: 2, name: 'Jerry'},
  {id: 3, name: 'Bob'}
]

export default function(props) {
  return (
    <div className={styles.normal}>
      <h1>Page User List</h1>
      <ul>
        {users.map(user => 
            // 通過點擊事件的方式跳轉
          <li key={user.id} onClick={() =>
          // 也可使用router.push(`/users/${user.id}`)
          props.history.push(`/users/${user.id}`)}>
            {/* <Link to={`/users/${user.id}`}>{user.name}</Link> */} // 通過標簽方式跳轉
            {user.name}
          </li>
        )}
      </ul>
    </div>
  );
}

4. config/config.js 配置路由

export default{
    routes: [
        {path: "/", component: "./index"}, // 是相對於pages
        {path: "/about", component: "./about", Routes: [
            "./routes/PrivateRoute.js"  // 是相對於根目錄的  
        ]}, // Routes  路由守衛
        {
            path: "/users",
            component: "./users/_layout"
            routes: [
                {path: "/users/", component: "./users/index"},
                {path: "users/:id", component: "./users/$id"}
            ]
        }
    ]
}

5. models/goods.js

export default {
    // "method url": (req, res) => {}
    "get /Api/goods": (req, res) => {
        setTimeout( () => {
            res.json({result: data})
        },300)
    }
}

6. umi models 示例

// goods.js

import axios from 'axios'

function getGoods(){
    return axios.get('/Api/goods')
}

export default{
    namespace: 'goods', // model的命名空間,若不定義則跟文件名同名
    // {title: 'WEB前端'},{title: 'WEB全棧'} 初始數據
    state: [], 
    effects: {// 異步操作
        *getList(action, {call, put}){
            const res = yield call(getGoods);
            yield put({type: 'initGoods', payload: res.data.result})
        }
    }, 
    reducers: {
        initGoods(state, action){
            return action.payload
        },
        // 更新狀態
        addGood(state, action){
            return [...state, { title: action.payload.title }]
        }
    }
}

// gooods. js 中代碼應用dva
import { connect } from 'dva'

@connect(
    state => ({
        goodsList: state.goods // 獲取指定命名空間的模型狀態
    }),
    {
        addGood: title => ({
            type: 'goods/addGood', // 命名空間+reducer組成名字
            payload: { title }
        }),
        getList: () => ({
            type: 'goods/getList' // 命名空間+effects組成名字
        })
    }
)

export default class extends React.Component{

    componentDidMount(){
        this.props.goodList()
    }

    render(){
        return (
            <div>
                <h2>Page Goods</h2>
                <ul>
                    { 
                        this.props.goodList.map(good =>
                            <li key={good.title}>
                                { good.title }
                            </li>
                    }
                </ul>
                <button onClick={() => this.props.addGood('商品'+ new Date().getTime())}>添加商品</button>
            </div>
        )
    }
}

7. umi 中使用antd

// config/config.js
export default{
    plugins: [
        "umi-plugin-react",
        {
            antd: true, // true為啟用
            dva: true
        }
    ]
}

8. 攔截器在全局下的應用——global.js

9. src/app.js——修改dva的配置

export default dva = {
    config: {
        onStateChange(state){
            if (localstorage) {
                localStorage.setItem('cart', JSON.stringify(state.cart))
            }
        }        
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM