redux
- redux是近年來javascript中火熱的狀態管理容器,提供可預測的全局狀態管理。在大型的應用中咱們常採用redux來進行狀態管理,redux的基本使用方式以下
- 使用redux,咱們先要進行action的編寫,action通常由type與其餘相關數據構成,下面就是簡單的兩個action
const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'
{ type: INCREMENT, payload: number }
{ type: DECREMENT, payload: number }
複製代碼
- 接下來,咱們就要根據action來進行咱們的reducer編寫,reducer是一個函數,具備兩個初始值,一個是當前的狀態值state,一個是當前的操做模式action
- 咱們要根據當前的操做模式進行相應的邏輯處理,並返回新的state,這裏咱們爲state設置一個初始值 0,對應INCREMENT與DECREMENT分別進行加減操做
const initialState = 0
const numberReducer = (state = initialState, action) => {
switch(action.type) {
case INCREMENT:
return state + action.payload
case DECREMENT:
return state - action.payload
default:
return state
}
}
複製代碼
- 上面只是定義了操做形式與如何響應該操做,並無實際的進行觸發,觸發狀態改變須要redux提供的dispatch,dispatch接收一個action並將這個action傳遞給reducer,從而觸發最後的狀態改變,以下
dispatch({ type: DECREMENT, payload: number })
複製代碼
react中使用redux
- react hooks出來以前,redux幾乎是全部react項目的不二隻選,可是其複雜的使用方式讓許多開發者都頭疼,對萌新來講更是要命,上網查了都不知道是怎麼回事
- hooks的出現,解放了一大批的react的開發者,易上手的開發模式讓開發者使用極其簡單,而react-redux天然也不會放過hooks的這波狂潮,下面就讓咱們對比一下hooks先後的兩種redux使用形式
react中使用redux
- react中使用redux須要藉助三方庫react-redux,react-redux提供了connect來讓咱們在組件中使用redux,以下使用
import React from 'react'
import { connect } from 'react-redux'
class Test extends React.Component {
constructor(){
super()
}
mapStateToProps(state) {
return {
number: state.number
}
}
mapDispatchToProps(dispatch) {
return {
increment: (number) => dispatch({ type: 'INCREMENT', payload: number }),
decrement: (number) => dispatch({ type: 'DECREMMENT', payload: number }),
}
}
render() {
return (
<div> <div>{ this.props.number }</div> <button onClick={() => { this.props.increment(10) }}>增長10</button> <button onClick={() => { this.props.decrement(5) }}>減小5</button> </div>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Test)
複製代碼
react hooks中使用redux
- hooks中使用redux須要依靠react-redux提供的 useSelector 與 useDispatch進行state取值與dispatch執行修改操做
- useSelector會根據接受的函數返回須要的狀態值,以下面的number
- useDispatch會返回一個操做函數,返回的操做函數能夠接收一個action執行狀態值的修改
import * as React from 'react'
import { useSelector, useDispatch } from 'react-redux'
const Test = () => {
const number = useSelector(state => state.number)
const dispatch = useDispatch()
return (
<div> <div>{ this.props.number }</div> <button onClick={() => { dispatch({ type: 'INCREMENT', payload: 10 }) }}>增長10</button> <button onClick={() => { dispatch({ type: 'DECREMMENT', payload: 5 }) }}>減小5</button> </div>
)
}
export default Test
複製代碼