介紹
React-Redux是Redux的官方React綁定庫餐禁。它能夠使你的React組件從Redux store中讀取數(shù)據(jù)驶赏,并且向store分發(fā)actions以更新數(shù)據(jù)
用原生redux和react結(jié)合使用的時(shí)候勋锤,每次都要載入store,而且派發(fā)完action修改數(shù)據(jù)后還要調(diào)用subscribe去監(jiān)聽栽燕,在監(jiān)聽里更新事件,React-Redux規(guī)避了這些麻煩稍刀。
React-Redux的三個(gè)關(guān)鍵作用
- 通過Provider把state注入到全局
- 通過connect把state和dispatch注入到當(dāng)前組建的props上
- 響應(yīng)式
安裝
yarn add react-redux
Provider
React-Redux 提供<Provider/>組件恬口,能夠使整個(gè)app訪問到Redux store中的數(shù)據(jù)。
Provider是用context封裝的弥锄。
connect
React-Redux提供一個(gè)connect方法能夠把組件和store連接起來丧靡,把state,dispatch方法籽暇,捏合到當(dāng)前組件上温治。
connect有兩個(gè)參數(shù),兩參數(shù)都是函數(shù)戒悠,參數(shù)在connect內(nèi)部被調(diào)用熬荆,參數(shù)內(nèi)能拿到state和dispatch,詳見代碼示例绸狐。
connect調(diào)用的返回結(jié)果是一個(gè)高階組件卤恳。
示例代碼
image.png
//index.js
import React from 'react';
import ReactDom from "react-dom"
//引入Provider
import {Provider} from "react-redux";
import Counter from "./counter/ReactReduxCounter";
import store from "./redux/basic/store"
ReactDom.render(
<Provider store={store}>
<Counter></Counter>
</Provider>,
document.getElementById("root")
)
//ReactReduxCounter.js
import React, { Component } from 'react';
import {connect} from "react-redux"
//子組件
class Counter extends Component {
//方法調(diào)用后自動(dòng)更新數(shù)據(jù)
increment=()=>{
this.props.increment()
}
decrement=()=>{
this.props.decrement()
}
render() {
return (
<div>
<div>{this.props.num}</div>
<button onClick={this.increment}>點(diǎn)我+1</button>
<button onClick={this.decrement}>點(diǎn)我-1</button>
</div>
);
}
}
//該函數(shù)作為connect的第一個(gè)參數(shù)累盗,能拿到state
//映射state到組建的props上
function mapStateToProps(state){
return {
num:state.counter
}
}
//該函數(shù)作為connect的第二個(gè)參數(shù),能拿到dispatch
//映射dispatch方法到組建的props上
function mapDispatchToProps(dispatch){
return {
increment(){
dispatch({
type:"increment"
})
},
decrement(){
dispatch({
type:"decrement"
})
}
}
}
//connet函數(shù)執(zhí)行返回一個(gè)高階組件
//調(diào)用這個(gè)高階組件突琳,傳入當(dāng)前組件Counter作為參數(shù),返回一個(gè)增強(qiáng)的Counter組件
//這個(gè)增強(qiáng)的組件props里有store的state和dispach方法
export default connect( mapStateToProps , mapDispatchToProps )(Counter)
//store.js
import { createStore } from "redux"
const defaultState={
counter:0
}
//純函數(shù)
let reducers =(state = defaultState ,action)=>{
switch (action.type){
case "increment":
console.log("increment")
return {
counter:state.counter+1
}
case "decrement":
return {
counter:state.counter-1
}
default :
return state
}
}
const store = createStore(reducers)
export default store
如果文章能幫助到你若债,請給我點(diǎn)個(gè)贊吧!