const DELAY = 1000
let count = 0
count = count + 1
const user = 'world'
console.log(`hello ${user}`)
// 多行
const content = `
hello ${user}
thanks for you ${user}
`
console.log(content)
function logActivity(activity = 'skiing'){
console.log(activity)
}
logActivity() ;// skiing
[1, 2, 3].map(x => x + 1) // [2,3,4]
// 等同于
[1, 2, 3].map((function(x) {
return x + 1;
}).bind(this));
import dva from 'dva'
import {connect} from 'dva'
import * as service from './services'
export default App
export class App extends Component{}
// 对象
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)
}
const n = 'kk'
const a = 8
const u = {n , a}
// 定义对象的方法时,可省略去function
app.model({
reducers:{
add(){} // <=> add: function() {}
},
effects:{
*addRemote() {} // <=> addRemote: function() {}
}
})
// 组装数组
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}
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})
}
}
})
————————————————-重要内容—————————————————
函数
类
const attrs = {
href : 'http://exm.org',
target:'_blank'
}
<a {...attrs}>hello</a>
// 概念:由于js是弱类型语言,声明propTypes对props进行校验是有必要的
function App (props){
return <div>{props.name}</div>
}
App.propTypes = {
name:React.PropTypes.string.isRequired
}
.title {
color: red;
}
:global(.title) {
color: green;
}
//然后在引用的时候:
<App className={styles.title} /> // red
<App className="title" /> // green
/*
概念:在一些复杂的场景中,一个元素可能对应多个 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'/>
// 增删改 以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}
}
}
})
app2.model({
namespace:'todos',
effects:{
*addRemove({payload:todo},{put,call}){
yield call (addTodo,todo)
yield put({type:'add',payload:todo})
}
}
})
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)
app.model({
effects: {
*addRemote() {
try {
// Your Code Here
} catch(e) {
console.log(e.message);
}
},
},
});
fetch学习地址: https://github.com/github/fetch
import request from '../util/request'
//get
request('/api/todos')
// post
request ('/api/todos',{
methods:'post',
body:JSON.stringify({a:1})
})
app.model({
subscriptions:{
setup({dispatch,history}){
history.listen(({pathname})=>{
if(pathname === 'users'){
dispatch({
type:'users/fetch'
})
}
})
}
}
})
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,
}
})
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 }),
});
$ npm i dva-cli -g # 安装dva-cli
$ dva new myapp # 创建项目
$ cd myapp
$ npm start # 启动项目
手机扫一扫
移动阅读更方便
你可能感兴趣的文章