Hooks使用createStore、Provider、useSelector、useDispatch实现connect功能

简介: 使用React Hooks实现connect功能,通过createStore创建仓库,Provider提供store,useSelector获取state,useDispatch触发action,从而在函数式组件中管理状态,替代类组件中的connect功能。

connect

我们会用connect来包裹组件来让改组件使用到上级组件Provider的store
用法是connect(mapStateToProps,mapDispatchToProps)(组件)
使用的使用通过this.props.xxx来使用state,出发action的时候this.props.dispatch()

现在Hooks推出了很多hook来帮助我们实现更好的函数式组件编程。

下面我们实现一个小案例:

0.在app.js跟组件中使用Provider提供store
1.在子组件对redux中的信息进行展示
2.在子组件对年龄这个属性进行递增或者递减
3.在孙组件中对年龄进行重置0

最终样式

在这里插入图片描述

一、首先

我们需要准备我们的dispather函数和一些默认信息:
我们在src|store|index.js中写入以下内容,用于初始化store做准备:


export let initInfo = {
   
    name: "六卿",
    age: 18,
    habby: ["唱歌", "跳舞", "Run"]
}

export const ReduxFun = (state, action) => {
   
    switch (action.type) {
   
        case 'ageAdd':
            return {
   
                ...state,
                age: state.age + 1
            };
        case 'ageReduce':
            return {
   
                ...state,
                age: state.age - 1
            };
        case 'change0':
            console.log({
   
                ...state,
                age: 0
            })
            return {
   
                ...state,
                age: 0
            }
        default:
            return state
    }
}

我们使用export暴露的形式,所以我们在使用的时候需要使用解构的形式:

import {
    ReduxFun, initInfo } from './store/index'

二、其次

在App.js中,我们要引入store/index.js,我们要使用初始化好的默认值和dispatch函数

import A from './com/A'
import {
    ReduxFun, initInfo } from './store/index'
import {
    createStore } from "redux";
import {
    Provider} from 'react-redux'

function App() {
   
  let store = createStore(ReduxFun, initInfo)
  return (
    <div style={
   {
   border:"5px solid pink",width:"400px",margin:"0 auto",marginTop:"50px",paddingBottom:"30px"}}>
      <div style={
   {
   marginBottom:"30px"}}>我试试APP跟组件</div>
      <Provider store={
   store}>
        <A />
      </Provider>
    </div>
  );
}

export default App;

上面我们做的有两件事:
1:初始化store,使用redux中解构出来的createStore来创建,第一个参数是我们的dispatch函数,第二个参数是我们初始值(初始state)

let store = createStore(ReduxFun, initInfo)

2:将创建好的store通过react-redux中解构出来的Provider组件注入到后代组件中,store={store}

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

三、最终

1.在(A组件)子组件中使用APP_Provider的state以及修改age的值

首先看一下A组件的代码逻辑:

import React from 'react'
import Achild from './ACHILD'
import {
    useDispatch, useSelector } from 'react-redux'
const A = () => {
   
    let dispatch = useDispatch()
    const state = useSelector(state => state)
    const addAge = () => {
   
        dispatch({
    type: 'ageAdd' })
    }
    const ageReduce = () => {
   
        dispatch({
    type: 'ageReduce' })
    }
    return (
        <div style={
   {
    paddingLeft: "50px", width: "300px" }}>
            <div style={
   {
    border: "2px solid #ccc", marginTop: "30px", padding: "30px" }}>
                <div> 我是A组件</div>
                姓名:{
   state.name} <br />
                年龄:{
   state.age}<br />
                爱好:{
   state.habby.join(';')}<br />
                <div style={
   {
    marginTop: "30px" }}></div>
                <button style={
   {
    marginRight: "20px" }} onClick={
   addAge}>年龄增加1</button>
                <button onClick={
   ageReduce}>年龄减少1</button><br />
            </div>
            <Achild />
        </div>
    )
}
export default A

这个组件做了两件事:
1.展示state中的属性值:

//获取state中的值
const state = useSelector(state => state)
//在页面展示
 姓名:{
   state.name} <br />
 年龄:{
   state.age}<br />
 爱好:{
   state.habby.join(';')}<br />

2.改变age的值

//获取dispatch
 let dispatch = useDispatch()
 //点击事件
 <button style={
   {
    marginRight: "20px" }} onClick={
   addAge}>年龄增加1</button>
 <button onClick={
   ageReduce}>年龄减少1</button><br />
//方法函数
 const addAge = () => {
   
        dispatch({
    type: 'ageAdd' })
    }
 const ageReduce = () => {
   
        dispatch({
    type: 'ageReduce' })
    }

这个时候已经可以控制age的增加和减少了,现在我们要看一下孙组件改变state

2.(ACHILD组件)孙组件改变state
import React from 'react'
import {
    useDispatch } from 'react-redux'
const ACHILD = () => {
   
    let dispatch = useDispatch()
    const changeAge0 = () => {
   
        dispatch({
    type: 'change0' })
    }
    return (
        <div style={
   {
    border: "1px solid orange", marginTop: "30px", padding: "30px" }}>
            <div style={
   {
   marginBottom:"30px"}}> 我是ACHILD组件</div>
            <button onClick={
   changeAge0}>age重置0</button>
        </div>
    )
}
export default ACHILD

这个组件只做了一件事
1.出发redux中的dispatch方法,重置age的值

<button onClick={
   changeAge0}>age重置0</button>
let dispatch = useDispatch()
    const changeAge0 = () => {
   
        dispatch({
    type: 'change0' })
    }

四、总结

  1. 使用createStore来创建仓库;
  2. 使用Provider组件给后代注入创建好的store;
  3. 后代组件使用useSelector使用state;
  4. 后代组件使用useDispatch出发action改变state.

参考文章

1.React学习笔记——Hooks中useStore、useDispatch和useSelector的基础介绍和使用,以及两者替代connect
2.redux中使用useSelector、useDispatch替代connect

其他文章

1.hooks实现toDoList
2.hooks实现左添右减
3.React实现添加多行输入框(点击一行增加一行)
4.React页面跳转取消上一个页面的所有请求
5.React配合axios请求拦截校验session,403跳转至登陆页面

六卿

见贤思齐焉,见不贤内自省
目录
相关文章
|
前端开发 JavaScript BI
轻松搞定vue3+Pinia-2-修改state-patch-actions
轻松搞定vue3+Pinia-2-修改state-patch-actions
303 0
|
JSON Kubernetes 数据格式
K8S client-go Patch example
我在本文中主要会介绍使用client-go的Patch方式,主要包括strategic merge patch和json-patch
|
9月前
|
JavaScript 前端开发 开发者
vue3+ts配置跨域报错问题解决:> newpro2@0.1.0 serve > vue-cli-service serve ERROR Invalid options in vue.
【6月更文挑战第3天】在 Vue CLI 项目中遇到 &quot;ERROR Invalid options in vue.config.js: ‘server’ is not allowed&quot; 错误是因为尝试在 `vue.config.js` 中使用不被支持的 `server` 选项。正确配置开发服务器(如代理)应使用 `devServer` 对象,例如设置代理到 `http://xxx.com/`: ```javascript module.exports = { devServer: {
352 1
|
5月前
|
JavaScript 前端开发
JS高级—call(),apply(),bind()
【10月更文挑战第17天】call()`、`apply()`和`bind()`是 JavaScript 中非常重要的工具,它们为我们提供了灵活控制函数执行和`this`指向的能力。通过合理运用这些方法,可以实现更复杂的编程逻辑和功能,提升代码的质量和可维护性。你在实际开发中可以根据具体需求,选择合适的方法来满足业务需求,并不断探索它们的更多应用场景。
36 1
|
7月前
|
XML 数据格式
【Azure Logic App】在Logic App中使用 Transfer XML组件遇见错误 undefined
【Azure Logic App】在Logic App中使用 Transfer XML组件遇见错误 undefined
|
7月前
|
安全 API 网络架构
【Azure Logic App】使用 Easy Auth 在标准逻辑应用(Standard Logic App)中触发工作流
【Azure Logic App】使用 Easy Auth 在标准逻辑应用(Standard Logic App)中触发工作流
|
7月前
|
消息中间件 API C#
【Azure API 管理】APIM添加Log-to-eventhub的策略后,一些相关APIM与Event Hub的问题
【Azure API 管理】APIM添加Log-to-eventhub的策略后,一些相关APIM与Event Hub的问题
AxiosError: Network Error at XMLHttpRequest.handleError (webpack-internal:///./node_modules/axio
AxiosError: Network Error at XMLHttpRequest.handleError (webpack-internal:///./node_modules/axio
|
10月前
|
存储 JavaScript
深入理解 Vuex 中的this.$store.dispatch方法
深入理解 Vuex 中的this.$store.dispatch方法
深入理解 Vuex 中的this.$store.dispatch方法
Error:express-session deprecated undefined resave option; provide resave option app.js:17:10
Error:express-session deprecated undefined resave option; provide resave option app.js:17:10
Error:express-session deprecated undefined resave option; provide resave option app.js:17:10