溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Redux Hooks如何使用

發(fā)布時間:2022-11-14 09:17:39 來源:億速云 閱讀:119 作者:iii 欄目:web開發(fā)

這篇文章主要介紹“Redux Hooks如何使用”,在日常操作中,相信很多人在Redux Hooks如何使用問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”Redux Hooks如何使用”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

Redux Hooks

Redux中Hooks介紹

在之前的redux開發(fā)中,為了讓組件和redux結(jié)合起來,我們使用了react-redux庫中的connect:

但是這種方式必須使用高階函數(shù)結(jié)合返回的高階組件;

并且必須編寫:mapStateToProps和 mapDispatchToProps映射的函數(shù)。

在Redux7.1開始,提供了Hook的方式,在函數(shù)組件中再也不需要編寫connect以及對應(yīng)的映射函數(shù)了

useSelector的作用是將state映射到組件中:

參數(shù)一: 要求傳入一個回調(diào)函數(shù), 會將state傳遞到該回調(diào)函數(shù)中; 回調(diào)函數(shù)的返回值要求是一個對象, 在對象編寫要使用的數(shù)據(jù), 我們可以直接對這個返回的對象進行解構(gòu), 拿到我們要使用state中的數(shù)據(jù)

const { counter } = useSelector((state) => {
  return {
    counter: state.counter.counter
  }
})

參數(shù)二: 可以進行比較來決定是否組件重新渲染;

useSelector默認會比較我們返回的兩個對象是否相等;

如何可以比較呢?

  • 在useSelector的第二個參數(shù)中, 傳入react-redux庫中的shallowEqual函數(shù)就可以進行比較

import { shallowEqual } from 'react-redux'

const { counter } = useSelector((state) => ({
  counter: state.counter.counter
}), shallowEqual)

也就是我們必須返回兩個完全相等的對象才可以不引起重新渲染;

useDispatch非常簡單,就是調(diào)用useDispatch這個Hook, 就可以直接獲取到dispatch函數(shù),之后在組件中直接使用即可;

const dispatch = useDispatch()

我們還可以通過useStore來獲取當前的store對象(了解即可, 不建議直接操作store對象);


Redux中Hooks使用

我們來使用Redux的Hooks在App組件實現(xiàn)一個計數(shù)器, 在App的子組件中實現(xiàn)一個修改message的案例:

首先我們先創(chuàng)建一個簡單的store

// store/modules/counter.js

import { createSlice } from "@reduxjs/toolkit";

const counterSlice = createSlice({
  name: "counter",
  initialState: {
    counter: 10,
    message: "Hello World"
  },
  reducers: {
    changeNumberAction(state, { payload }) {
      state.counter = state.counter + payload
    },
    changeMessageAction(state,  {payload }) {
      state.message = payload
    }
  }
})

export const { changeNumberAction, changeMessageAction } = counterSlice.actions

export default counterSlice.reducer
// store/index.js

import { configureStore } from "@reduxjs/toolkit";
import counterSlice from "./modules/counter"

const store = configureStore({
  reducer: {
    counter: counterSlice
  }
})

export default store

要使用react-redux庫需要導入Provider對App組件進行包裹

import React from "react"
import ReactDOM from "react-dom/client"
import { Provider } from "react-redux"
import App from "./12_Redux中的Hooks/App"
import store from "./12_Redux中的Hooks/store"

const root = ReactDOM.createRoot(document.querySelector("#root"))

root.render(
  <Provider store={store}>
    <App/>
  </Provider>
)

在組件時使用useSelector和useDispatch實現(xiàn)獲取store中的數(shù)據(jù)和修改store中數(shù)據(jù)的操作

import React, { memo } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { changeMessageAction, changeNumberAction } from './store/modules/counter'

// 子組件Home
const Home = memo(() => {
  console.log("Home組件重新渲染")
  
  // 通過useSelector獲取到store中的數(shù)據(jù)
  const { message } = useSelector((state) => ({
    message: state.counter.message
  }))

  // useDispatch獲取到dispatch函數(shù)
  const dispatch = useDispatch()
  function changeMessage() {
    dispatch(changeMessageAction("Hello ChenYq"))
  }

  return (
    <div>
      <h3>{message}</h3>
      <button onClick={changeMessage}>修改message</button>
    </div>
  )
})


// 根組件App
const App = memo(() => {
  console.log("App組件重新渲染")
  
  // 通過useSelector獲取到store中的數(shù)據(jù)
  const { counter } = useSelector((state) => ({
    counter: state.counter.counter
  }))

  // useDispatch獲取到dispatch函數(shù)
  const dispatch = useDispatch()
  function changeNumber(num) {
    dispatch(changeNumberAction(num))
  }
  
  return (
    <div>
      <h3>當前計數(shù): {counter}</h3>
      <button onClick={() => changeNumber(1)}>+1</button>
      <button onClick={() => changeNumber(-1)}>-1</button>

      <Home/>
    </div>
  )
})

export default App

現(xiàn)在我們已經(jīng)在組件中使用并且修改了了store中的數(shù)據(jù), 但是現(xiàn)在還有一個小問題(性能優(yōu)化)

當App組件中修改了counter時, App組件會重新渲染這個是沒問題的; 但是Home組件中使用的是message, 并沒有使用counter, 卻也會重新渲染; 同樣的在Home子組件中修改了message, 根組件App也會重新渲染; 這是因為在默認情況下useSelector是監(jiān)聽的整個state, 當state發(fā)生改變就會導致組件重新渲染

要解決這個問題就需要使用useSelector的第二個參數(shù)來控制是否需要重新渲染, 我們只需要在useSelector函數(shù)中傳入react-redux庫中的shallowEqual函數(shù)即可, 它內(nèi)部會自動進行一個淺層比較, 當使用的state中的數(shù)據(jù)確實發(fā)生變化的時候才會重新渲染

import React, { memo } from 'react'
import { useDispatch, useSelector, shallowEqual } from 'react-redux'
import { changeMessageAction, changeNumberAction } from './store/modules/counter'

// 子組件Home
const Home = memo(() => {
  console.log("Home組件重新渲染")

  const { message } = useSelector((state) => ({
    message: state.counter.message
  }), shallowEqual)

  const dispatch = useDispatch()
  function changeMessage() {
    dispatch(changeMessageAction("Hello ChenYq"))
  }

  return (
    <div>
      <h3>{message}</h3>
      <button onClick={changeMessage}>修改message</button>
    </div>
  )
})


// 根組件App
const App = memo(() => {
  console.log("App組件重新渲染")

  // 通過useSelector獲取到store中的數(shù)據(jù)
  const { counter } = useSelector((state) => ({
    counter: state.counter.counter
  }), shallowEqual)

  // useDispatch獲取到dispatch函數(shù)
  const dispatch = useDispatch()
  function changeNumber(num) {
    dispatch(changeNumberAction(num))
  }
  
  return (
    <div>
      <h3>當前計數(shù): {counter}</h3>
      <button onClick={() => changeNumber(1)}>+1</button>
      <button onClick={() => changeNumber(-1)}>-1</button>

      <Home/>
    </div>
  )
})

export default App

到此,關(guān)于“Redux Hooks如何使用”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關(guān)知識,請繼續(xù)關(guān)注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI