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')
})
/*
概述: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})
}
}
})
7. React Component
7.1 组件定义的方式
函数
类
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/fetch
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.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.1 通过dva-cli创建项目
$ npm i dva-cli -g # 安装dva-cli
$ dva new myapp # 创建项目
$ cd myapp
$ npm start # 启动项目