React使用redux基础操作详解

 更新时间:2023年01月13日 15:15:04   作者:web老猴子  
这篇文章主要介绍了如何在React中直接使用Redux,目前redux在react中使用是最多的,所以我们需要将之前编写的redux代码,融入到react当中去,本文给大家详细讲解,需要的朋友可以参考下

一,什么是redux

Redux是一个用来管理管理数据状态和UI状态的JavaScript应用工具。随着JavaScript单页应用(SPA)开发日趋复杂,JavaScript需要管理比任何时候都要多的state(状态),Redux就是降低管理难度的。(Redux支持React,Angular、jQuery甚至纯JavaScript) react-redux工作流程 安装redux

npm install --save redux

简单使用

在src下新建store文件夹,创建仓库管理文件index.js

import { createStore, applyMiddleware, compose } from 'redux'  // 引入createStore方法
import reducer from "./reducer"
const store = createStore(reducer) // 创建数据存储仓库
export default store                 //暴露出去 

同时创建reducer.js文件

//定义初始state
const defaultState = {
  inputValue: '请输入待办事项',
  list: [
    '早上4点起床,锻炼身体',
    '中午下班游泳一小时']
}
export default (state = defaultState, action) => {
  return state
} 

组件中使用state的值

import React, { Component } from 'react';
//组件中引入store
import store from './store'
class TodoList extends Component {
  constructor(props) {
    super(props)
    #获取store中state的值
    this.state = store.getState();
    this.clickBtn = this.clickBtn.bind(this)
​}
  render() {
    return (
           <div>
                <Input placeholder={this.state.inputValue} style={{ width: '250px', marginRight: '10px' }}  value={this.state.inputValue} />
                <Button type="primary" onClick={clickBtn}>增加</Button>
            </div>
            <div style={{ margin: '10px', width: '300px' }}>
                <List bordered
                    dataSource={this.state.list}
                    renderItem={(item, index) => (<List.Item onClick={() => {
                       deleteItem(index)
                  }}>{item}</List.Item>)}></List>
            </div>
  );}deleteItem(index) {console.log(index)}
}
export default TodoList; 

二,安装redux谷歌调试工具

翻墙下载redux_dev_tool, 在store/index文件下添加

import { createStore, applyMiddleware, compose } from 'redux'  // 引入createStore方法
import reducer from "./reducer"
//const composeEnhancers = 
//const enhancers = composeEnhancers(applyMiddleware(thunk)) 
const store = createStore(
                           reducer,
                           window.__REDUX_DEVTOOLS_EXTENSION_ && window.__REDUX_DEVTOOLS_EXTENSION_()
                         ) // 创建数据存储仓库,存在调试工具,开启工具
export default store 

三,操作store 改变

import React, { Component } from 'react';
//组件中引入store
import store from './store'
class TodoList extends Component {
  constructor(props) {
    super(props)
    #获取store中state的值
    this.state = store.getState();
    this.clickBtn = this.clickBtn.bind(this)this.changeInputValue = this.changeInputValue.bind(this)
    #添加订阅 #新版本不用添加订阅 但是input value变化需要使用订阅
    store.subscribe(this.storeChange)
    this.storeChange = this.storeChange.bind(this)}
  render() {
    return (
           <div>
                <Input placeholder={this.state.inputValue} style={{ width: '250px', marginRight: '10px' }} onChange={()=>{this.changeInputValue}  value={this.state.inputValue} />
                <Button type="primary" onClick={this.clickBtn}>增加</Button>
            </div>
            <div style={{ margin: '10px', width: '300px' }}>
                <List bordered
                    dataSource={this.state.list}
                    renderItem={(item, index) => (
                      <List.Item onClick={() => {deleteItem(index)}}>{item}</List.Item>)}></List>
            </div>
  );}changeInputValue(e){//声明action对象
    const action ={
  type:'changeInput',
      value:e.target.value
  }
    //调用dispatch
    store.dispatch(action)}
  // 订阅更新
  storeChange() {
    this.setState(store.getState())}// 添加按钮事件clickBtn(){const action ={
  type:'addItem',
  }store.dispatch(action)}//点击删除事件deleteItem(index) {
    const action = {
  type:'deleteItem',
      index
  }
    store.dispatch(action)}
}
export default TodoList; 

在reducer.js中

//定义初始state
const defaultState = {
  inputValue: '请输入待办事项',
  list: [
    '早上4点起床,锻炼身体',
    '中午下班游泳一小时']
}
export default (state = defaultState, action) => {
  #reducer里只能接受state 不能改变state
  if(action.type == 'changeInput'){
    let newState = JSON.pares(JSON.stringify(state)) //深拷贝state
    newState.inputValue = action.value
    return newState}
  //添加事件
  if(action.type == 'addItem'){
    let newState = JSON.pares(JSON.stringify(state)) //深拷贝state
    newState.list.push(newState.inputValue)
    newState.inputValue = '' //增加完成,设置为空
    return newState}
  //删除事件
  if(action.type == 'deleteItem'){
    let newState = JSON.pares(JSON.stringify(state)) //深拷贝state
    newState.list.splice(action.index,1)
    return newState}
  return state
} 

四,写redux的小技巧

在store中新建文件actionType.js

//定义常量
export const CHANGE_INPUT = 'changeInput'
export const ADD_ITEM = 'addItem'
export const DELETE_ITEM = 'deleteItem'
export const GET_LIST = 'getList' 

在组件中引入actionType文件

import React, { Component } from 'react';
//组件中引入store
import store from './store'
import { CHANGE_INPUT, ADD_ITEM, DELETE_ITEM, GET_LIST } from './store/actionType'
class TodoList extends Component {
  constructor(props) {
    super(props)
    #获取store中state的值
    this.state = store.getState();
    this.clickBtn = this.clickBtn.bind(this)this.changeInputValue = this.changeInputValue.bind(this)
    #添加订阅 #新版本不用添加订阅 但是input value变化需要使用订阅
    store.subscribe(this.storeChange)
    this.storeChange = this.storeChange.bind(this)}
  render() {
    return (
           <div>
                <Input placeholder={this.state.inputValue} style={{ width: '250px', marginRight: '10px' }} onChange={()=>{this.changeInputValue}  value={this.state.inputValue} />
                <Button type="primary" onClick={this.clickBtn}>增加</Button>
            </div>
            <div style={{ margin: '10px', width: '300px' }}>
                <List bordered
                    dataSource={this.state.list}
                    renderItem={(item, index) => (
                      <List.Item onClick={() => {deleteItem(index)}}>{item}</List.Item>)}></List>
            </div>
  );}changeInputValue(e){//声明action对象
    #使用引入的常量替换
    const action ={
  type:CHANGE_INPUT,
      value:e.target.value
  }
    //调用dispatch
    store.dispatch(action)}
  // 订阅更新
  storeChange() {
    this.setState(store.getState())}// 添加按钮事件clickBtn(){const action ={
  type:ADD_ITEM,
  }store.dispatch(action)}//点击删除事件deleteItem(index) {
    const action = {
  type:DELETE_ITEM,
      index
  }
    store.dispatch(action)}
}
export default TodoList; 

在reducer.js中也进行引入

import { CHANGE_INPUT, ADD_ITEM, DELETE_ITEM } from './actionType'
//定义初始state
const defaultState = {
  inputValue: '请输入待办事项',
  list: [
    '早上4点起床,锻炼身体',
    '中午下班游泳一小时']
}
export default (state = defaultState, action) => {
  #reducer里只能接受state 不能改变state
  if(action.type == CHANGE_INPUT){
    let newState = JSON.pares(JSON.stringify(state)) //深拷贝state
    newState.inputValue = action.value
    return newState}
  //添加事件
  if(action.type == ADD_ITEM){
    let newState = JSON.pares(JSON.stringify(state)) //深拷贝state
    newState.list.push(newState.inputValue)
    newState.inputValue = '' //增加完成,设置为空
    return newState}
  //删除事件
  if(action.type == DELETE_ITEM){
    let newState = JSON.pares(JSON.stringify(state)) //深拷贝state
    newState.list.splice(action.index,1)
    return newState}
  return state
} 

集中整理action派发

在store中新建actionCreator.js文件

import { CHANGE_INPUT, ADD_ITEM, DELETE_ITEM } from './actionType'
export const changeInputAction = (value) =>({type:CHANGE_INPUT,
  value
})
export const addItemAction = () =>({type:ADD_ITEM,
})
export const deleteItemAction = (index) =>({type:DELETE_ITEM,
  index
}) 

在组件中引入actionCreator.js

import React, { Component } from 'react';
//组件中引入store
import store from './store'
//引入actionCreator.js
import { changeInputAction,addItemAction,deleteItemAction } from './store/actionCreator'
class TodoList extends Component {
  constructor(props) {
    super(props)
    #获取store中state的值
    this.state = store.getState();
    this.clickBtn = this.clickBtn.bind(this)this.changeInputValue = this.changeInputValue.bind(this)
    #添加订阅 #新版本不用添加订阅 但是input value变化需要使用订阅
    store.subscribe(this.storeChange)
    this.storeChange = this.storeChange.bind(this)}
  render() {
    return (
           <div>
                <Input placeholder={this.state.inputValue} style={{ width: '250px', marginRight: '10px' }} onChange={()=>{this.changeInputValue}  value={this.state.inputValue} />
                <Button type="primary" onClick={this.clickBtn}>增加</Button>
            </div>
            <div style={{ margin: '10px', width: '300px' }}>
                <List bordered
                    dataSource={this.state.list}
                    renderItem={(item, index) => (
                      <List.Item onClick={() => {deleteItem(index)}}>{item}</List.Item>)}></List>
            </div>
  );}changeInputValue(e){
    const action = changeInputAction(e.target.value)
    //调用dispatch
    store.dispatch(action)}
  // 订阅更新
  storeChange() {
    this.setState(store.getState())}// 添加按钮事件clickBtn(){const action =addItemAction()store.dispatch(action)}//点击删除事件deleteItem(index) {
    const action = deleteItemAction(index)
    store.dispatch(action)}
}
export default TodoList; 

到此这篇关于React使用redux基础操作详解的文章就介绍到这了,更多相关React使用redux内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • 基于React Hooks的小型状态管理详解

    基于React Hooks的小型状态管理详解

    本文主要介绍一种基于 React Hooks 的状态共享方案,介绍其实现,并总结一下使用感受,目的是在状态管理方面提供多一种选择方式。感兴趣的小伙伴可以了解一下
    2021-12-12
  • 浅谈React Native 传参的几种方式(小结)

    浅谈React Native 传参的几种方式(小结)

    这篇文章主要介绍了浅谈React Native 传参的几种方式,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-05-05
  • react项目如何运行在微信公众号

    react项目如何运行在微信公众号

    这篇文章主要介绍了react项目如何运行在微信公众号,帮助大家更好的理解和学习使用react,感兴趣的朋友可以了解下
    2021-04-04
  • React中使用Axios发起POST请求提交文件方式

    React中使用Axios发起POST请求提交文件方式

    这篇文章主要介绍了React中使用Axios发起POST请求提交文件方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-02-02
  • React使用xlsx和js-export-excel实现前端导出

    React使用xlsx和js-export-excel实现前端导出

    这篇文章主要为大家详细介绍了React如何分别使用xlsx和js-export-excel实现前端导出功能,文中的示例代码讲解详细,感兴趣的小伙伴可以了解下
    2024-02-02
  • React Native预设占位placeholder的使用

    React Native预设占位placeholder的使用

    本篇文章主要介绍了React Native预设占位placeholder的使用,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-09-09
  • React项目打包发布到Tomcat页面空白问题及解决

    React项目打包发布到Tomcat页面空白问题及解决

    这篇文章主要介绍了React项目打包发布到Tomcat页面空白问题及解决方案,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-06-06
  • React中路由的参数传递路由的配置文件详解

    React中路由的参数传递路由的配置文件详解

    路由的配置文件目前我们所有的路由定义都是直接使用Route组件,并且添加属性来完成的,路由的参数传递有二种方式这,两种方式在Router6.x中都是提供的hook函数的API, 类组件需要通过高阶组件的方式使用,本文通过示例代码详解讲解,需要的朋友参考下吧
    2022-11-11
  • React封装全屏弹框的方法

    React封装全屏弹框的方法

    这篇文章主要为大家详细介绍了React封装全屏弹框的方法,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-08-08
  • 详解在React中跨组件分发状态的三种方法

    详解在React中跨组件分发状态的三种方法

    这篇文章主要介绍了详解在React中跨组件分发状态的三种方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-08-08

最新评论