日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

react-redux的基本使用_React

作者:是張魚(yú)小丸子鴨 ? 更新時(shí)間: 2022-10-08 編程語(yǔ)言

react-redux和redux的關(guān)系?

redux是react中進(jìn)行狀態(tài)管理的js庫(kù)(不是react插件),一般是管理多個(gè)組件中共享數(shù)據(jù)狀態(tài),和vue中的vuex是一樣的

react-redux是redux官方react綁定庫(kù),能夠使react組件從redux store中讀取數(shù)據(jù),并且向store分發(fā)actions以此來(lái)更新數(shù)據(jù),說(shuō)白了就是用于連接redux,它提供了connect和Provider兩個(gè)Api

react-redux基本使用

1.安裝

npm i react-redux@7 --save

盡量安裝8.0以下的版本,8.0以上會(huì)報(bào)錯(cuò),無(wú)法使用connect方法,提示hooks錯(cuò)誤,provider也無(wú)法使用

2.配置

首先,我們?cè)谌肟谖募信渲胷eact-redux的Provider方法,綁定store的redux對(duì)象數(shù)據(jù)

//導(dǎo)入react-redux的provier的組件
import { Provider } from "react-redux"
//...other
root.render(
  <Provider store={store}>
      <Routes />
  </Provider>
);

?注意:Provider的store參數(shù)必須寫(xiě),如果不寫(xiě),他會(huì)報(bào)錯(cuò),他的原理跟我們使用context狀態(tài)樹(shù)中給provider傳遞的value值一樣

3.組件中使用

在我們要使用的組件中嘗試連接react-redux連接redux的數(shù)據(jù)

使用步驟

  • 導(dǎo)入react-redux依賴包,引入connect方法
  • connect有兩個(gè)函數(shù)參數(shù),mapStateToProps和mapDispatchToProps
  • 把redux中state數(shù)據(jù)和action方法直接映射到組件props屬性中去
  • 組件中可以直接通過(guò)props使用redux中的數(shù)據(jù),調(diào)用方法直接調(diào)用redux中的action的數(shù)據(jù)
  • connect( mapStateToProps,mapDispatchToProps)(組件名)

代碼展示

import React from 'react';
import { connect } from 'react-redux';
 
export default function ReactRedux(props) {
    console.log(props);
  return (
    <div>
        <h3>react-redux</h3>
    </div>
  )
}
/把redux中的state數(shù)據(jù)映射到組件內(nèi)部的變量
const mapStateToProps=(state)=>{
    console.log(state);
    return {
        ...state
    }
}
//把redux中action的操作,可以映射成為組件的props的內(nèi)部函數(shù)
const mapDispathToProps=(dispatch)=>{
     return {
        plus:()=>dispatch({type:'PLUS'})
     }
}
//連接redux的操作的方法
ReactRedux=connect(mapStateToProps,mapDispathToProps)(ReactRedux)

connect方法執(zhí)行完成以后綁定當(dāng)前組件,復(fù)制完直接拋出即可

我們打印props中的數(shù)據(jù)會(huì)發(fā)現(xiàn)我們store中數(shù)據(jù)會(huì)作為props中屬性給我們打印出來(lái)

這樣,我們就可以使用props.屬性/方法進(jìn)行使用

原文鏈接:https://blog.csdn.net/qq_60976312/article/details/126273117

欄目分類
最近更新