DVA知識集合

react與dva

原文地址:https://github.com/dvajs/dva-knowledgemapcss

1.變量聲明

const DELAY = 1000 let count = 0 count = count + 1

2. 模板字符串

const user = 'world' console.log(`hello ${user}`) // 多行 const content = ` hello ${user} thanks for you ${user} ` console.log(content)

3. 默認參數

function logActivity(activity = 'skiing'){ console.log(activity) } logActivity() ;// skiing

4. 箭頭函數

[1, 2, 3].map(x => x + 1) // [2,3,4] // 等同於 [1, 2, 3].map((function(x) { return x + 1; }).bind(this));

5. 模塊的Import 和 Export

import dva from 'dva' import {connect} from 'dva' import * as service from './services' export default App export class App extends Component{}

 

6. ES6對象和數組

6.1 析構賦值

// 對象 const people = {name:'kk',age:12} const { name , age } = people console.log(`${name}:${age}`) // 數組 const arr = [1,2] const [foo,bar] = arr console.log(foo) // 函數 const add = (state,{payload}) => { return state.concat(payload) } // alias別名 const plus = (state,{payload:todo}) => { return state.concat(todo) }

6.2 對象字面量

const n = 'kk' const a = 8 const u = {n , a} // 定義對象的方法時,可省略去function app.model({ reducers:{ add(){} // <=> add: function() {} }, effects:{ *addRemote() {} // <=> addRemote: function() {} } })

6.3 展開符 Spread Operator

// 組裝數組 const array = ['add'] // [...array,'remove'] // 獲取部分項 function directions(first,...rest){ console.log(rest) } console.log(directions('a','b','c')) // 代替apply function fun(x,y,z){ console.log(y) } const args = [1,2,3] fun.apply(null,args) // 等同於 fun(...args) // 合成新的object const old = { a:1 } const change = { b:2 } const ret = {...old , ...change}

 

6.4 Promises

fetch('/api/todos') .then(res => res.json()) .then(data => ({data})) .catch(err => ({err})) // 定義promise const delay = (timeout) => { return new Promise(resolve => { setTimeout(resolve,timeout) }) } delay(1000).then(_ => { console.log('executed') })

 

6.5 Generators 生成器

/* 概述:dva 的 effects 是經過 generator 組織的。Generator 返回的是迭代器,經過 yield 關鍵字實現暫停功能。 這是一個典型的 dva effect,經過 yield 把異步邏輯經過同步的方式組織起來。 */ app.model({ namespace:'todos', effects:{ *addRemove({payload:todo},{put,call}){ yield call(addTodo,todo) yield put({type:'add',payload:todo}) } } })

 

————————————————-重要內容—————————————————react

7. React Component

7.1 組件定義的方式

函數git

es6

7.2 JSX

7.2.1 擴充組件的props
const attrs = { href : 'http://exm.org', target:'_blank' } <a {...attrs}>hello</a> 

 

7.3 Props

7.3.1 propTypes
// 概念:因爲js是弱類型語言,聲明propTypes對props進行校驗是有必要的 function App (props){ return <div>{props.name}</div> } App.propTypes = { name:React.PropTypes.string.isRequired }

 

7.4 Css Modules

.title { color: red; } :global(.title) { color: green; }
//而後在引用的時候: <App className={styles.title} /> // red <App className="title" /> // green

 

7.5 classnames Package

/* 概念:在一些複雜的場景中,一個元素可能對應多個 className,而每一個 className 又基於一些條件來決定是否出現。 這時,classnames 這個庫就很是有用。 */ import classnames from 'classnames' const App = (props) => { const cls = (props) => { btn : true, btnLarge:props.type === 'submit', btnSmall:props.type === 'edit' } return <div classNames={cls}> } //這樣傳入不一樣的type給App組件,就會返回不一樣的className組合 <App type='submit'/> <App type='edit'/>

7.6 Reducer
// 增刪改 以todo爲例 app.model({ namespace:'todos', state:[], reducers:{ add(state,{payload:todo}){ return state.concat(todo) }, remove(state,{payload:id}){ return state.filter(todo => todo.id !== id) }, update(state,{payload:updatedTodo}){ return state.map(todo=>{ if(todo.id === updatedTodo.id){ return {...todo,...updatedTodo} }else{ return todo } }) } } })
// 嵌套數據的增刪改 app1.model({ namespace:'app', state:{ todos:[], loading:false, }, reducers:{ add(state,{payload:todo}){ const todos = state.todos.concat(todo) return {...state,todos} } } })

7.7 Effect

app2.model({
    namespace:'todos', effects:{ *addRemove({payload:todo},{put,call}){ yield call (addTodo,todo) yield put({type:'add',payload:todo}) } } })

 

7.7.1 put 用於出發action
yield put({ type: 'todos/add', payload: 'Learn Dva' }); // 7.7.2 call 用於調用異步邏輯 支持promise const result = yield call(fetch, '/todos'); // 7.7.3 select 從state中獲取數據 const todos = yield select(state => state.todos)

 

7.7.3 錯誤的處理
app.model({
  effects: {
    *addRemote() {
      try { // Your Code Here } catch(e) { console.log(e.message); } }, }, });

 

7.8 異步請求 whatwg-fetch

fetch學習地址: https://github.com/github/fetchgithub

7.8.1 get 和 post

import request from '../util/request' //get request('/api/todos') // post request ('/api/todos',{ methods:'post', body:JSON.stringify({a:1}) }) 

 

7.9 Subscription 訂閱 異步數據的初始化

app.model({
    subscriptions:{
        setup({dispatch,history}){
            history.listen(({pathname})=>{
                if(pathname === 'users'){ dispatch({ type:'users/fetch' }) } }) } } })

 

7.10 路由 基於action進行頁面跳轉

import {routerRedux} from 'dva/router' // inside effects yield put(routerRedux.push('/logout')) // outside effects dispatch(routerRedux.push('/logout')) // with query routerRedux.push({ pathname:'/logout', query:{ page:2, } })

 

8.0 dva的配置

8.1 Redux Middleware 添加中間件

import createLogger from 'redux-logger' const app = dva ({ onAction:createLogger() // onAction支持數組,可同時傳入多箇中間件 }) // history 切換history爲browserHistory import {browserHistory} from 'dva/router' const ap = dva({ history:browserHistory }) //去除 hashHistory 下的 _k 查詢參數 import { useRouterHistory } from 'dva/router'; import { createHashHistory } from 'history'; const app2 = dva({ history: useRouterHistory(createHashHistory)({ queryKey: false }), });

9.0 工具

9.1 經過dva-cli建立項目

$ npm i dva-cli -g # 安裝dva-cli $ dva new myapp # 建立項目 $ cd myapp $ npm start # 啓動項目 
相關文章
相關標籤/搜索