轉載 原文:https://blog.csdn.net/zhangrui_web/article/details/79651812css
不知你們學 react 或 dva 時會不會有這樣的疑惑:html
這篇文檔梳理了基於 dva-cli 使用 dva 的最小知識集,讓你能夠用最少的時間掌握建立相似 dva-hackernews 的所有知識,而且不須要掌握額外的冗餘知識。react
不要用 var
,而是用 const
和 let
,分別表示常量和變量。不一樣於 var
的函數做用域,const
和 let
都是塊級做用域。git
const DELAY = 1000; let count = 0; count = count + 1;
模板字符串提供了另外一種作字符串組合的方法。es6
const user = 'world'; console.log(`hello ${user}`); // hello world // 多行 const content = ` Hello ${firstName}, Thanks for ordering ${qty} tickets to ${event}. `;
function logActivity(activity = 'skiing') { console.log(activity); } logActivity(); // skiing
函數的快捷寫法,不須要經過 function
關鍵字建立函數,而且還能夠省略 return
關鍵字。github
同時,箭頭函數還會繼承當前上下文的 this
關鍵字。web
好比:json
[1, 2, 3].map(x => x + 1); // [2, 3, 4]
等同於:redux
[1, 2, 3].map((function(x) { return x + 1; }).bind(this));
import
用於引入模塊,export
用於導出模塊。api
好比:
// 引入所有 import dva from 'dva'; // 引入部分 import { connect } from 'dva'; import { Link, Route } from 'dva/router'; // 引入所有並做爲 github 對象 import * as github from './services/github'; // 導出默認 export default App; // 部分導出,需 import { App } from './file'; 引入 export class App extend Component {};
析構賦值讓咱們從 Object 或 Array 裏取部分數據存爲變量。
// 對象 const user = { name: 'guanguan', age: 2 }; const { name, age } = user; console.log(`${name} : ${age}`); // guanguan : 2 // 數組 const arr = [1, 2]; const [foo, bar] = arr; console.log(foo); // 1
咱們也能夠析構傳入的函數參數。
const add = (state, { payload }) => { return state.concat(payload); };
析構時還能夠配 alias,讓代碼更具備語義。
const add = (state, { payload: todo }) => { return state.concat(todo); };
這是析構的反向操做,用於從新組織一個 Object 。
const name = 'duoduo'; const age = 8; const user = { name, age }; // { name: 'duoduo', age: 8 }
定義對象方法時,還能夠省去 function
關鍵字。
app.model({ reducers: { add() {} // 等同於 add: function() {} }, effects: { *addRemote() {} // 等同於 addRemote: function*() {} }, });
Spread Operator 即 3 個點 ...
,有幾種不一樣的使用方法。
可用於組裝數組。
const todos = ['Learn dva']; [...todos, 'Learn antd']; // ['Learn dva', 'Learn antd']
也可用於獲取數組的部分項。
const arr = ['a', 'b', 'c']; const [first, ...rest] = arr; rest; // ['b', 'c'] // With ignore const [first, , ...rest] = arr; rest; // ['c']
還可收集函數參數爲數組。
function directions(first, ...rest) { console.log(rest); } directions('a', 'b', 'c'); // ['b', 'c'];
代替 apply。
function foo(x, y, z) {} const args = [1,2,3]; // 下面兩句效果相同 foo.apply(null, args); foo(...args);
對於 Object 而言,用於組合成新的 Object 。(ES2017 stage-2 proposal)
const foo = { a: 1, b: 2, }; const bar = { b: 3, c: 2, }; const d = 4; const ret = { ...foo, ...bar, d }; // { a:1, b:3, c:2, d:4 }
此外,在 JSX 中 Spread Operator 還可用於擴展 props,詳見 Spread Attributes。
Promise 用於更優雅地處理異步請求。好比發起異步請求:
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'); });
dva 的 effects 是經過 generator 組織的。Generator 返回的是迭代器,經過 yield
關鍵字實現暫停功能。
這是一個典型的 dva effect,經過 yield
把異步邏輯經過同步的方式組織起來。
app.model({ namespace: 'todos', effects: { *addRemote({ payload: todo }, { put, call }) { yield call(addTodo, todo); yield put({ type: 'add', payload: todo }); }, }, });
React Component 有 3 種定義方式,分別是 React.createClass
, class
和 Stateless Functional Component
。推薦儘可能使用最後一種,保持簡潔和無狀態。這是函數,不是 Object,沒有 this
做用域,是 pure function。
好比定義 App Component 。
function App(props) { function handleClick() { props.dispatch({ type: 'app/create' }); } return <div onClick={handleClick}>${props.name}</div> }
等同於:
class App extends React.Component { handleClick() { this.props.dispatch({ type: 'app/create' }); } render() { return <div onClick={this.handleClick.bind(this)}>${this.props.name}</div> } }
相似 HTML,JSX 裏能夠給組件添加子組件。
<App>
<Header /> <MainContent /> <Footer /> </App>
class
是保留詞,因此添加樣式時,需用 className
代替 class
。
<h1 className="fancy">Hello dva</h1>
JavaScript 表達式須要用 {}
括起來,會執行並返回結果。
好比:
<h1>{ this.props.title }</h1>
能夠把數組映射爲 JSX 元素列表。
<ul> { this.props.todos.map((todo, i) => <li key={i}>{todo}</li>) } </ul>
儘可能別用 //
作單行註釋。
<h1> {/* multiline comment */} {/* multi line comment */} { // single line } Hello </h1>
這是 JSX 從 ECMAScript6 借鑑過來的頗有用的特性,用於擴充組件 props 。
好比:
const attrs = { href: 'http://example.org', target: '_blank', }; <a {...attrs}>Hello</a>
等同於
const attrs = { href: 'http://example.org', target: '_blank', }; <a href={attrs.href} target={attrs.target}>Hello</a>
數據處理在 React 中是很是重要的概念之一,分別能夠經過 props, state 和 context 來處理數據。而在 dva 應用裏,你只需關心 props 。
JavaScript 是弱類型語言,因此請儘可能聲明 propTypes 對 props 進行校驗,以減小沒必要要的問題。
function App(props) { return <div>{props.name}</div>; } App.propTypes = { name: React.PropTypes.string.isRequired, };
內置的 prop type 有:
一張圖理解 CSS Modules 的工做原理:
button
class 在構建以後會被重命名爲 ProductList_button_1FU0u
。button
是 local name,而 ProductList_button_1FU0u
是 global name 。你能夠用簡短的描述性名字,而不須要關心命名衝突問題。
而後你要作的所有事情就是在 css/less 文件裏寫 .button {...}
,並在組件裏經過 styles.button
來引用他。
CSS Modules 默認是局部做用域的,想要聲明一個全局規則,可用 :global
語法。
好比:
.title {
color: red; } :global(.title) { color: green; }
而後在引用的時候:
<App className={styles.title} /> // red <App className="title" /> // green
classnames
Package在一些複雜的場景中,一個元素可能對應多個 className,而每一個 className 又基於一些條件來決定是否出現。這時,classnames 這個庫就很是有用。
import classnames from 'classnames'; const App = (props) => { const cls = classnames({ btn: true, btnLarge: props.type === 'submit', btnSmall: props.type === 'edit', }); return <div className={ cls } />; }
這樣,傳入不一樣的 type 給 App 組件,就會返回不一樣的 className 組合:
<App type="submit" /> // btn btnLarge <App type="edit" /> // btn btnSmall
reducer 是一個函數,接受 state 和 action,返回老的或新的 state 。即:(state, action) => state
以 todos 爲例。
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; } }); }, }, };
建議最多一層嵌套,以保持 state 的扁平化,深層嵌套會讓 reducer 很難寫和難以維護。
app.model({ namespace: 'app', state: { todos: [], loading: false, }, reducers: { add(state, { payload: todo }) { const todos = state.todos.concat(todo); return { ...state, todos }; }, }, });
下面是深層嵌套的例子,應儘可能避免。
app.model({ namespace: 'app', state: { a: { b: { todos: [], loading: false, }, }, }, reducers: { add(state, { payload: todo }) { const todos = state.a.b.todos.concat(todo); const b = { ...state.a.b, todos }; const a = { ...state.a, b }; return { ...state, a }; }, }, });
示例:
app.model({ namespace: 'todos', effects: { *addRemote({ payload: todo }, { put, call }) { yield call(addTodo, todo); yield put({ type: 'add', payload: todo }); }, }, });
用於觸發 action 。
yield put({ type: 'todos/add', payload: 'Learn Dva' });
用於調用異步邏輯,支持 promise 。
const result = yield call(fetch, '/todos');
用於從 state 裏獲取數據。
const todos = yield select(state => state.todos);
dva 裏,effects 和 subscriptions 的拋錯所有會走 onError
hook,因此能夠在 onError
裏統一處理錯誤。
const app = dva({ onError(e, dispatch) { console.log(e.message); }, });
而後 effects 裏的拋錯和 reject 的 promise 就都會被捕獲到了。
若是須要對某些 effects 的錯誤進行特殊處理,須要在 effect 內部加 try catch
。
app.model({ effects: { *addRemote() { try { // Your Code Here } catch(e) { console.log(e.message); } }, }, });
異步請求基於 whatwg-fetch,API 詳見:https://github.com/github/fetch
import request from '../util/request'; // GET request('/api/todos'); // POST request('/api/todos', { method: 'POST', body: JSON.stringify({ a: 1 }), });
假如約定後臺返回如下格式時,作統一的錯誤處理。
{
status: 'error', message: '', }
編輯 utils/request.js
,加入如下中間件:
function parseErrorMessage({ data }) { const { status, message } = data; if (status === 'error') { throw new Error(message); } return { data }; }
而後,這類錯誤就會走到 onError
hook 裏。
subscriptions
是訂閱,用於訂閱一個數據源,而後根據須要 dispatch 相應的 action。數據源能夠是當前的時間、服務器的 websocket 鏈接、keyboard 輸入、geolocation 變化、history 路由變化等等。格式爲 ({ dispatch, history }) => unsubscribe
。
好比:當用戶進入 /users
頁面時,觸發 action users/fetch
加載用戶數據。
app.model({ subscriptions: { setup({ dispatch, history }) { history.listen(({ pathname }) => { if (pathname === '/users') { dispatch({ type: 'users/fetch', }); } }); }, }, });
path-to-regexp
Package若是 url 規則比較複雜,好比 /users/:userId/search
,那麼匹配和 userId 的獲取都會比較麻煩。這是推薦用 path-to-regexp簡化這部分邏輯。
import pathToRegexp from 'path-to-regexp'; // in subscription const match = pathToRegexp('/users/:userId/search').exec(pathname); if (match) { const userId = match[1]; // dispatch action with userId }
<Route path="/" component={App}> <Route path="accounts" component={Accounts}/> <Route path="statements" component={Statements}/> </Route>
詳見:react-router
Route Components 是指 ./src/routes/
目錄下的文件,他們是 ./src/router.js
裏匹配的 Component。
好比:
import { connect } from 'dva'; function App() {} function mapStateToProps(state, ownProps) { return { users: state.users, }; } export default connect(mapStateToProps)(App);
而後在 App 裏就有了 dispatch
和 users
兩個屬性。
Route Component 會有額外的 props 用以獲取路由信息。
更多詳見:react-router
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, }, });
除 push(location)
外還有更多方法,詳見 react-router-redux
好比要添加 redux-logger 中間件:
import createLogger from 'redux-logger'; const app = dva({ onAction: createLogger(), });
注:onAction 支持數組,可同時傳入多箇中間件。
import { browserHistory } from 'dva/router'; const app = dva({ history: browserHistory, });
import { useRouterHistory } from 'dva/router'; import { createHashHistory } from 'history'; const app = dva({ history: useRouterHistory(createHashHistory)({ queryKey: false }), });