生活随笔
收集整理的這篇文章主要介紹了
1 redux初探、用react开发数值增值案例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
含義
Redux是專門用作狀態(tài)管理的js庫,不是react插件庫 可以用在react、angular、vue等項(xiàng)目中 能集中式管理react應(yīng)用中多個組件共享的狀態(tài)
使用
npx create
- react
- app redux1
cnpm install redux
- S
關(guān)鍵字
store reducer action subscribe
案例
1. 創(chuàng)建store、并傳入reducer
import { createStore
} from 'redux'
import { counter
} from './redux/reducers'
const store
= createStore ( counter
)
2. 使用dispatch
store
. dispatch ( { type : '' , data
: '' ,
} )
3. reducer里處理數(shù)據(jù)
function counter ( state
= 0 , action
) { const { type , data
} = action
}
4. 監(jiān)聽state,觸發(fā)更新
store
. getState ( )
store
. subscribe ( render
)
import ReactDOM
from 'react-dom'
import App
from './App'
import { createStore
} from 'redux'
import { counter
} from './redux/reducers'
const store
= createStore ( counter
)
store
. subscribe ( render
)
function render ( ) { ReactDOM
. render ( < App store
= { store
} / > , document
. getElementById ( 'root' ) )
}
render ( )
export function counter ( state
= 0 , action
) { const { type , data
} = action
console . log ( 'reduce 觸發(fā)了方法' , type ) console . log ( 'reduce 接收參數(shù)' , data
) switch ( type ) { case 'add' : return state
+ data
case 'minus' : return state
- data
case 'add_odd' : if ( data
% 2 !== 0 ) { return state
+ data
} case 'add_delay' : setTimeout ( ( ) => { return state
+ data
} , 1000 ) default : return state
}
}
export function add ( param
) { return { type : 'add' , data
: param
}
}
export function minus ( param
) { return { type : 'minus' , data
: param
}
}
export function add_odd ( param
) { return { type : 'add_odd' , data
: param
}
}
export function add_delay ( param
) { return { type : 'add_delay' , data
: param
}
}
import React
, { Component
, createRef
} from 'react'
import * as actions
from './redux/action' export default class App extends Component { constructor ( props
) { super ( props
) this . selectRef
= createRef ( ) } compute = ( method
) => { const selectDom
= this . selectRef
. current
, selectVal
= Number ( selectDom
. value
) , store
= this . props
. store
; console . log ( 'app store/method' , store
, method
) store
. dispatch ( actions
[ method
] ( selectVal
) ) } render ( ) { const count
= this . props
. store
. getState ( ) console . log ( '重新render了' , count
) return ( < > < h1
> 數(shù)值:
{ count
} < / h1
> < select ref
= { this . selectRef
} > < option value
= "1" > 1 < / option
> < option value
= "2" > 2 < / option
> < option value
= "3" > 3 < / option
> < / select
> & nbsp
; < button onClick
= { ( ) => this . compute ( 'add' ) } > + < / button
> & nbsp
; < button onClick
= { ( ) => this . compute ( 'minus' ) } > - < / button
> & nbsp
; < button onClick
= { ( ) => this . compute ( 'add_odd' ) } > 奇數(shù)加
< / button
> & nbsp
; < button onClick
= { ( ) => this . compute ( 'add_delay' ) } > 延遲加
< / button
> < / > ) }
}
總結(jié)
以上是生活随笔 為你收集整理的1 redux初探、用react开发数值增值案例 的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔 網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔 推薦給好友。