日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

使用useSelector useDispatch 替代connect

 Coder編程 2020-03-01

前言

隨著react hooks越來越火,react-redux也緊隨其后發(fā)布了7.1(https://react-redux./ap...

首先是幾個(gè)API

  • useSelector()
const result : any = useSelector(selector : Function, equalityFn? : Function)

主要作用:
reduxstore對(duì)象中提取數(shù)據(jù)(state)。

注意:選擇器函數(shù)應(yīng)該是純函數(shù),因?yàn)樗赡茉谌我鈺r(shí)間點(diǎn)多次執(zhí)行。
import React from 'react'
import { useSelector } from 'react-redux'

export const CounterComponent = () => {
  const counter = useSelector(state => state.counter)
  return <div>{counter}</div>
}
  • useDispatch()
const dispatch = useDispatch()

返回Redux store中對(duì)dispatch函數(shù)的引用。你可以根據(jù)需要使用它。

import React from 'react'
import { useDispatch } from 'react-redux'

export const CounterComponent = ({ value }) => {
  const dispatch = useDispatch()

  return (
    <div>
      <span>{value}</span>
      <button onClick={() => dispatch({ type: 'increment-counter' })}>
        Increment counter
      </button>
    </div>
  )
}

將回調(diào)使用dispatch傳遞給子組件時(shí),建議使用來進(jìn)行回調(diào)useCallback,因?yàn)榉駝t,由于更改了引用,子組件可能會(huì)不必要地呈現(xiàn)。

import React, { useCallback } from 'react'
import { useDispatch } from 'react-redux'

export const CounterComponent = ({ value }) => {
  const dispatch = useDispatch()
  const incrementCounter = useCallback(
    () => dispatch({ type: 'increment-counter' }),
    [dispatch]
  )

  return (
    <div>
      <span>{value}</span>
      <MyIncrementButton onIncrement={incrementCounter} />
    </div>
  )
}

export const MyIncrementButton = React.memo(({ onIncrement }) => (
  <button onClick={onIncrement}>Increment counter</button>
))
  • useStore()
const store = useStore()

這個(gè)Hook返回redux <Provider>組件的store對(duì)象的引用。

這個(gè)鉤子應(yīng)該不長(zhǎng)被使用。useSelector應(yīng)該作為你的首選。但是,有時(shí)候也很有用。來看個(gè)例子:

import React from 'react'
import { useStore } from 'react-redux'

export const CounterComponent = ({ value }) => {
  const store = useStore()

  // 僅僅是個(gè)例子! 不要在你的應(yīng)用中這樣做.
  // 如果store中的state改變,這個(gè)將不會(huì)自動(dòng)更新
  return <div>{store.getState()}</div>
}

dva中如何使用

dvadva@2.6.0[1]的beta版本發(fā)布了這幾個(gè)API,如果我們想使用他,首先安裝指定版本的

yarn add dva@2.6.0-beta.19 
// or
npm install dva@2.6.0-beta.19

并且這樣使用

import { useSelector, useDispatch } from 'dva';

如果不想升級(jí)dva版本的話我們需要安裝

yarn add react-redux@7.1.0

并且這樣使用

import { useSelector, useDispatch } from 'react-redux';

首先先看原始dva的寫法
先定義一個(gè)user model

// 1.user.js ==>model
export default {
  namespace: 'user',
  state: {
    userInfo:null,
  },
  effects: {
      *fetchUser({paylaod},{call,put}){
          const res = yield(api,payload)
          yield put({
            type: 'save',
            payload: {
                userInfo:res   
            },
          });
      }
  },
  reducers:{
      save(state, { payload }) {
        return {
            ...state,
            ...payload,
        };
      },
  }
}

然后在頁(yè)面中使用


import {connect} from 'dva'

const Home = props=>{
    // 獲取數(shù)據(jù)
    const {user,loading,dispatch} = props
    
    // 發(fā)起請(qǐng)求
    useEffect(()=>{
        dispatch({
            type:'user/fetchUser',payload:{}
        })
    },[])
    
    // 渲染頁(yè)面
    if(loading) return <div>loading...</div>
    return (
        <div>{user.name}<div>
    )
}

export default connect(({loading,user})=>({
    loading:loading.effects['user/fetchUser'],
    user:user.userInfo
}))(Home)

connect這個(gè)高階組件里定義了太多東西,這種寫法太惡心了。
如果太多數(shù)據(jù)從props獲取的話,connect里堆了太多代碼

下面我們使用useDispatch useSelector 優(yōu)化上面的代碼

import {useDispatch,useSelector} from 'dva'

const Home = props=>{
    
    const dispatch = useDispatch()
    
    const loadingEffect = useSelector(state =>state.loading);
    const loading = loadingEffect.effects['user/fetchUser'];
    const user = useSelector(state=>state.user.userInfo)
    
    // 發(fā)起請(qǐng)求
    useEffect(()=>{
        dispatch({
            type:'user/fetchUser',payload:{}
        })
    },[])
    
    // 渲染頁(yè)面
    if(loading) return <div>loading...</div>
    return (
        <div>{user.name}<div>
    )
}

export default Home

使用useSelector useDispatch 替代connect

關(guān)于

  • 本文首發(fā)于使用useSelector useDispatch 替代connect

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購(gòu)買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多