阅读 1001

redux中使用useSelector、useDispatch替代connect

Hooks 提供了很多好用的api,甚至很多人认为Hooks的useReducer等Api已经可以取代Redux了。其实Hooks和Redux的使用场景并不冲突,而且可以互相借鉴,最近react-edux最新版本(7.1)也引入了Hooks风格的Api。

useStateuseReducer是Hooks中最常用的Api,适合用来进行简单的状态管理,但也都有一些无法满足的需求

useState


import React, { useState } from "react";

const ComponentUseState = () => {
  const [num, setNum] = useState(0);

  return (
    <div>
      <h2>Using useState</h2>
      Number: {num}
      <button onClick={() => setNum(num + 1)}>+</button>
      <button onClick={() => setNum(num - 1)}>-</button>
    </div>
  );
};

export default ComponentUseState;
复制代码

useState可以用最简单的方式更新状态,但是状态更新的逻辑(例如上面例子中的加减一运算)散落在UI中,不能独立复用,也不便于测试。

useReducer


使用useReducer可以解决上面useState无法解决的问题。

import React, { useReducer } from 'react'

const initialState = {num: 0};

const reducer = (state, action) => {
  switch(action.type) {
    case 'decrement':
      return {...state, num: state.num - 1}
    case 'increment':
      return {...state, num: state.num + 1}
    default:
      return state;
  }
}

const ComponentUseReducer = () => {
  const [state, dispatch] = useReducer(reducer, initialState)

  const { num } = state
  return (
    <div>
      <h2>Using useReducer</h2>
      Number: {num}
      <button onClick={() => dispatch({type: 'increment'})}>+</button>
      <button onClick={() => dispatch({type: 'decrement'})}>-</button>
    </div>
  );
};

export default ComponentUseReducer;
复制代码

可以看到useReducer的逻辑脱离了UI,可以独立复用。reducer就是一个单纯的Js方法,我们可以对reducer进行单独测试,甚至可以在chrome中进行调试

实际使用中reducer应该以单独的文件存在,上面例子为了简单起见放到了一起。

useReducer虽然很好地分离了逻辑和UI,但是无法像redux一样进行跨组件的状态共享,例如子组件无法方便的访问到num

useSelector、useDispatch


如上所述,Hooks仍然无法替代Redux的作用,特别是在状态共享方面。庆幸的是 react-redux 7.1之后也可以使用useSelector、useDispatch等HooksApi替代connect,减少模板代码。

import React from "react";
import { createStore } from "redux";
import { Provider, useSelector, useDispatch } from "react-redux";

const initialState = { num: 0 };

const reducer = (state, action) => {
  switch (action.type) {
    case "decrement":
      return { ...state, num: state.num - 1 };
    case "increment":
      return { ...state, num: state.num + 1 };
    default:
    
      return state;
  }
};

const store = createStore(reducer, initialState);

const ComponentUseReactRedux = () => {
  return (
    <div>
      <h2>ComponentUseReactRedux</h2>
      <Provider store={store}>
        <ChildComponentUseReactRedux />
      </Provider>
    </div>
  )
}

const ChildComponentUseReactRedux = () => {
  const num = useSelector(state => state.num);
  const dispatch = useDispatch();
  return (
    <div>
      <h3>Using useSelector, useDispatch</h3>
      Number: {num}
      <button onClick={() => dispatch({ type: "increment" })}>+</button>
      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
    </div>
  );
};

export default ComponentUseReactRedux;
复制代码

createStore

通过createStore将state存入store,

const store = createStore(reducer, initialState);
复制代码

再通过Provider向子组件暴露store,通过store在父子组件之间共享状态

 <Provider store={store}>
     <ChildComponentUseReactRedux />
 </Provider>
复制代码

useSelector

子组件可以通过useSelector访问name

  const num = useSelector(state => state.num);
复制代码

当然,也可以提出selector函数,方便替换和复用,如下

const selector = state => {
  return state.num;
}

const num = useSelector(selector);
复制代码

useDispatch

通过useDispatch 可以获取dispatch

  const dispatch = useDispatch()
复制代码

即使多几个子组件也可以共享状态

const ComponentUseReactRedux = () => {
  return (
    <div>
      <h2>ComponentUseReactRedux</h2>
      <Provider store={store}>
        <ChildComponentUseReactRedux />
        <ChildComponentUseReactRedux />
      </Provider>
    </div>
  )
}
复制代码

在这里插入图片描述

最后


通过useSelector、useDispatch等方法,我们可以用Hooks方法完成Redux的功能,Hooks和Redux之间没有替代关系,应该更好地共存和融合。

文章分类
前端
文章标签