React中使用redux

  1. 要將store注入到組件當(dāng)中,必須用<Provider store={store對(duì)象}></Provider>標(biāo)簽將組件包裹
    ??<Provider></Provider>組件引入自"react-redux"核心包
import { Provider } from 'react-redux';
import store from './store/index';

  <Provider store={store}>
    <App />
  </Provider>

2."react-redux"核心包為我們提供的鉤子函數(shù)

  • ①useSelector(state => {}) 用來(lái)抓取store中存儲(chǔ)的state數(shù)據(jù)
    1.其中形參state獲取的是所有切片中的state集合
    2.函數(shù)中通過(guò)返回 state.name (name為store中各切片的屬性名),來(lái)提取各切片數(shù)據(jù)
    3.此時(shí),調(diào)用useSelector()函數(shù)會(huì)返回回調(diào)函數(shù)中的返回值,用一個(gè)變量接收該對(duì)象即可
  const student = useSelector(state => state.student)
  console.log(student.age);
  • ②useDispatch()獲取派發(fā)器對(duì)象,此鉤子函數(shù)無(wú)需傳參
import { useDispatch } from "react-redux";
const dispatch = useDispatch()

引入切片頁(yè)面中暴露的action創(chuàng)建器(例如setName、setAge等),然后作為調(diào)用dispatch時(shí)的參數(shù)即可

import { setName,setAge } from "./store";
  const nameHandler = () => {
    dispatch(setName({name:'楊玉蟬'}))
  }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容