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

學無先后,達者為師

網站首頁 編程語言 正文

React?Hooks?-?useContetx和useReducer的使用實例詳解_React

作者:藍桉cyq ? 更新時間: 2022-12-22 編程語言

useContetx的使用

在之前的開發中,我們要在組件中使用共享的Context有兩種方式:

類組件可以通過 類名.contextType = MyContext 的方式,在類中獲取context;

多個Context或者在函數式組件中通過 MyContext.Consumer 方式共享context;

但是多個Context共享時的方式會存在大量的嵌套(會導致代碼閱讀性非常差):

Context Hook允許我們通過Hook來直接獲取某個Context的值, 相對于class組件中的使用方式會簡單非常多;

例如定義兩個Context

import { createContext } from "react";

const InfoContext = createContext()
const ThemeContext = createContext()

export {
  InfoContext,
  ThemeContext
}

依然需要使用InfoContext和ThemeContext將組件包裹起來

const root = ReactDOM.createRoot(document.querySelector("#root"))
root.render(
  <InfoContext.Provider value={{name: "chenyq", age: 18}}>
    <ThemeContext.Provider value={{color: "red"}}>
      <App/>
    </ThemeContext.Provider>
  </InfoContext.Provider>
)

在要使用的地方, 通過useContetx這個hook函數可以直接獲取到值

import React, { memo } from 'react'
import { useContext } from 'react'
import { InfoContext, ThemeContext } from './index'

const App = memo(() => {
  // 通過hook拿到共享的數據
  const info = useContext(InfoContext)
  const theme = useContext(ThemeContext)
  return (
    <div>
      {/* 展示共享的數據 */}
      <h2>{info.name}-{info.age}</h2>
      <h2>{theme.color}</h2>
    </div>
  )
})

export default App

注意事項:

當組件上層最近的 <MyContext.Provider> 更新時,該 Hook 會觸發重新渲染,并使用最新的值傳遞給 MyContext provider 的 context value 值。

useReducer的使用

很多人看到useReducer的第一反應應該是redux的某個替代品,其實并不是。

useReducer僅僅是useState的一種替代方案:

在某些場景下,如果state的處理邏輯比較復雜,我們可以通過useReducer來對其進行拆分;

或者這次修改的state需要依賴之前的state時,也可以使用;

useReducer函數使用過程如下:

例如我們先定義一個reducer函數

// 定義一個reducer函數
function reducer(state, action) {
  switch(action.type) {
    case "incremment":
      return {...state, counter: state.counter + action.num}
    case "decremment":
      return {...state, counter: state.counter - action.num}
    default: 
      return state
  }
}

再在函數組件中通過useReducer函數將我們定義的reducer函數使用起來

import React, { memo } from 'react'
import { useReducer } from 'react'

// 定義一個reducer函數
function reducer(state, action) {
  switch(action.type) {
    case "incremment":
      return {...state, counter: state.counter + action.num}
    case "decremment":
      return {...state, counter: state.counter - action.num}
    default: 
      return state
  }
}

// 函數組件
const App = memo(() => {
  // 第一個參數傳reducer, 第二個參數初始化值
  const [state, dispatch] = useReducer(reducer, { counter: 0 })

  return (
    <div>
      {/* 使用reducer函數中的state */}
      <h2>當前計數: {state.counter}</h2>
      {/* 派發action通過reducer函數修改counter */}
      <button onClick={() => dispatch({type: "incremment", num: 5})}>+5</button>
      <button onClick={() => dispatch({type: "decremment", num: 5})}>-5</button>
    </div>
  )
})

export default App

數據是不會共享的,它們只是使用了相同的counterReducer的函數而已。

所以,useReducer只是useState的一種替代品,并不能替代Redux。

原文鏈接:https://lanan.blog.csdn.net/article/details/127490498

欄目分類
最近更新