react中redux的使用方式

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


提示:以下是本篇文章正文内容,下面案例可供参考

一、redux是什么?

redux是一个可以用于react项目的数据管理仓库,类似于vue3中的pinia。 

二、使用步骤

1、精简版

1、首先创建一个store.js文件

代码如下(示例):

// 引入createStore,专门用于创建redux中最为核心的store对象

import { legacy_createStore as createStore } from 'redux'

import countReducer from './count_reducer'

const store = createStore(countReducer)

export default store

2、创建一个处理数据的函数reducer.js(仅供参考我是这么理解的)

代码如下(示例):

// 1、该文件适用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数

// 2、reducer函数会接到俩个参数,分别为:之前的状态(preState),动作对象(action)

const initState = 0

function countReducer (preState = initState, action) {

  const { type, data } = action

  // 根据type决定如何加工数据

  switch (type) {

    case 'increment':

      return preState + data

    case 'decrement':

      return preState - data

    default:

      return preState

  }

}

export default countReducer

3、使用方式(为了方便直接上代码块吧)

1、引入store

import store from '../../redux/store'

2、读取仓库数据

store.getState()

3、派发指令,说明你想干什么(type:为指令这是自己定义的,data:为传到仓库的数据)

 store.dispatch({ type: 'increment', data: value * 1 })

4、想要页面更新需要监听一下

  componentDidMount() {

    // 监测到redux中的状态改变了,就调用render

    store.subscribe(() => {

      // 函数体(这里利用只要调用了setState,就会触发组件的render(),重新渲染页面)

      this.setState({})

    })

  }

完整代码

import React, { Component } from 'react'

import store from '../../redux/store'

export default class Count extends Component {

  // 这里可以后期优化到index.js中去,避免在每个组件中调用

  componentDidMount() {

    // 监测到redux中的状态改变了,就调用render

    store.subscribe(() => {

      // 函数体(这里利用只要调用了setState,就会触发组件的render(),重新渲染页面)

      this.setState({})

    })

  }

  increment = () => {

    const { value } = this.selectNumber

    store.dispatch({ type: 'increment', data: value * 1 })

  }

  decrement = () => {

    const { value } = this.selectNumber

    store.dispatch({ type: 'decrement', data: value * 1 })

  }

  incrementIfOdd = () => {

    const { value } = this.selectNumber

    const count = store.getState()

    if (count % 2 !== 0) {

      store.dispatch({ type: 'increment', data: value * 1 })

    }

  }

  incrementAsync = () => {

    const { value } = this.selectNumber

    setTimeout(() => {

      store.dispatch({ type: 'increment', data: value * 1 })

    }, 1000)

  }

  render() {

    return (

      <div>

        <h1>当前求和为:{store.getState()}</h1>

        <select ref={(c) => (this.selectNumber = c)}>

          <option value="1">1</option>

          <option value="2">2</option>

          <option value="3">3</option>

        </select>

        &nbsp;

        <button onClick={this.increment}>+</button>&nbsp;

        <button onClick={this.decrement}>-</button>&nbsp;

        <button onClick={this.incrementIfOdd}>当前求和为奇数在加</button>&nbsp;

        <button onClick={this.incrementAsync}>异步加</button>&nbsp;

      </div>

    )

  }

}

2、完整版 

相较于精简版版,完整版多了constant.js常量文件与action.js文件

1、constant.js

/**

 * 该模块用于定义action对象中type类型的常量值,方便统一化管理已经避免程序员写错单词

 */

export const INCREMENT = 'increment'

export const DECREMENT = 'decrement'

2、 action.js

/**

 * 该文件专门为Count组件生成action对象,方便统一修改和在组件中引入直接使用

 */

import { INCREMENT, DECREMENT } from './constant'

export const createIncrementAction = (data) => ({ type: INCREMENT, data })

export const createDecrementAction = (data) => ({ type: DECREMENT, data })

3、reducer.js

使用方式大同小异

// 1、该文件适用于创建一个为Count组件服务的reducer,reducer的本质就是一个函数

// 2、reducer函数会接到俩个参数,分别为:之前的状态(preState),动作对象(action)

import { INCREMENT,DECREMENT } from "./constant"

const initState = 0

function countReducer (preState = initState, action) {

  const { type, data } = action

  // 根据type决定如何加工数据

  switch (type) {

    case INCREMENT:

      return preState + data

    case DECREMENT:

      return preState - data

    default:

      return preState

  }

}

export default countReducer

 4、组件中使用

直接替换精简版中store.dispatch()中的代码即可

import {createIncrementAction,createDecrementAction} from '../../redux/count_action'

store.dispatch(createIncrementAction(value*1))

store.dispatch(createDecrementAction(value*1))

 3、异步action版(一般在需要异步请求拿数据时使用,当然也完全可以在组件中发请求拿数据,使用同步请求更新页面。)

同步action,就是指调用action.js里的函数返回的值为对象

异步action,就是指调用action.js里的函数返回的值为函数,异步action中一般都会调用同步action

 1、使用前还要安装redux-thunk这个库以及从redux中引入applyMiddleware

store.js的配置也变了

// 引入createStore,专门用于创建redux中最为核心的store对象

import { legacy_createStore as createStore, applyMiddleware } from 'redux'

import countReducer from './count_reducer'

// 引入redux-thunk,用于支持异步action

import {thunk} from 'redux-thunk'

export default createStore(countReducer, applyMiddleware(thunk))

2、action.js

/**

 * 该文件专门为Count组件生成action对象

 * 对象型的是同步action

 * 函数型的是异步action

 */

// 同步action,就是指action的值为对象

import { INCREMENT, DECREMENT } from './constant'

export const createIncrementAction = (data) => ({ type: INCREMENT, data })

export const createDecrementAction = (data) => ({ type: DECREMENT, data })

// 异步action,就是指action的值为函数,异步action中一般都会调用同步action

export const createIncrementAsyncAction = (data, time) => {

  return (dispatch) => {

    setTimeout(() => {

      dispatch(createIncrementAction(data))

    }, time)

  }

}

3、组件中使用 

import {

  createIncrementAsyncAction

} from '../../redux/count_action'

store.dispatch(createIncrementAsyncAction(value * 1,500))

总结

本文只是记录自己在学习react过程,仅供参考。有任何不对欢迎大佬指正。

  • 36
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
最新版的 react-redux 使用方法如下: 首先,确保你的项目已经安装了 react-redux 依赖包。你可以使用以下命令安装它: ``` npm install react-redux ``` 或 ``` yarn add react-redux ``` 接下来,你需要创建一个 Redux store。你可以使用 Redux Toolkit 来简化这个过程。首先,导入 `configureStore` 和 `getDefaultMiddleware` 函数: ``` import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit'; ``` 然后,创建一个 rootReducer 来合并你的所有 reducer: ``` import { combineReducers } from 'redux'; const rootReducer = combineReducers({ // 这里是你的 reducer }); ``` 接着,使用 `configureStore` 函数创建 Redux store。你可以通过传入一个对象来配置 store,例如指定 reducer、middleware 等等。以下是一个示例: ``` const store = configureStore({ reducer: rootReducer, middleware: getDefaultMiddleware() }); ``` 现在,你可以使用 `<Provider>` 组件来将 Redux store 提供给你的整个应用程序。在你的根组件,导入 `<Provider>` 组件和你的 Redux store,然后将其包裹在应用的最外层: ``` import { Provider } from 'react-redux'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); ``` 通过将 Redux store 提供给整个应用程序,你可以在应用的任何地方使用 `useSelector` 和 `useDispatch` 钩子来访问 Redux store 的状态和分发 action。例如,在你的组件,你可以这样使用: ``` import { useSelector, useDispatch } from 'react-redux'; const MyComponent = () => { const counter = useSelector(state => state.counter); const dispatch = useDispatch(); // 使用 counter 和 dispatch }; ``` 这就是最新版的 react-redux使用方法。你可以根据你的具体需求,自定义配置和使用其他相关的 react-redux API。希望对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值