React使用redux基础操作详解

目录
  • 一,什么是redux
  • 二,安装redux谷歌调试工具
  • 三,操作store 改变
  • 四,写redux的小技巧

一,什么是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内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • React状态管理Redux的使用介绍详解

    目录 1. 简介 2. 核心概念 3. redux工作流 4. 模拟redux工作流程 5. 使用redux 6. react-redux 1. 简介 Redux 是 JavaScript 应用的状态容器(对象),提供可预测的状态管理.可以让你开发出行为稳定可预测的应用,运行于不同的环境(客户端.服务器.原生应用),并且易于测试.Redux 除了和 React 一起用外,还支持其它界面库. 解决的问题:多层级组件间通信问题. 2. 核心概念 单一数据源 整个redux中的数据都是集中管理,存储于

  • React redux 原理及使用详解

    目录 概述 createStore创建store applyMiddleware 应用中间件 combineReducers 合并多个reducer dispatch 中间件 中间件的调用顺序 store redux 数据流 bindActionCreators compose enhancer 使用 redux 常遇见的问题 概述 一个状态管理工具 Store:保存数据的地方,你可以把它看成一个容器,整个应用只能有一个 Store. State:包含所有数据,如果想得到某个时点的数据,就要对

  • React Redux应用示例详解

    目录 一 React-Redux的应用 1.学习文档 2.Redux的需求 3.什么是Redux 4.什么情况下需要使用redux 二.最新React-Redux 的流程 安装Redux Toolkit 创建一个 React Redux 应用 基础示例 Redux Toolkit 示例 三.使用教程 安装Redux Toolkit和React-Redux​ 创建 Redux Store​ 为React提供Redux Store​ 创建Redux State Slice​ 将Slice Reduc

  • React Flux与Redux设计及使用原理

    目录 1. redux介绍及设计和使用的三大原则 2. redux工作流 3. redux原理解析 4. reducer 扩展 5. redux中间件 6. Redux DevTools Extension Flux 是一种架构思想,专门解决软件的结构问题.它跟MVC架构是同一类东西,但是更加简单和清晰.Flux存在多种实现(至少15种) Facebook Flux是用来构建客户端Web应用的应用架构.它利用单向数据流的方式来组合React 中的视图组件.它更像一个模式而不是一个正式的框架,开发

  • 如何在React中直接使用Redux

    React中使用Redux 开始之前需要强调一下,redux和react没有直接的关系,你完全可以在React, Angular, Ember, jQuery, or vanilla JavaScript中使用Redux. 尽管这样说,redux依然是和React库结合的更好,因为他们是通过state函数来描述界面的状态,Redux可以发射状态的更新, 让他们作出相应; 目前redux在react中使用是最多的,所以我们需要将之前编写的redux代码,融入到react当中去. 这里我创建了两个组

  • React中Redux核心原理深入分析

    目录 一.Redux是什么 二.Redux的核心思想 三.Redux中间件原理 四.手写一个Redux 总结 一.Redux是什么 众所周知,Redux最早运用于React框架中,是一个全局状态管理器.Redux解决了在开发过程中数据无限层层传递而引发的一系列问题,因此我们有必要来了解一下Redux到底是如何实现的? 二.Redux的核心思想 Redux主要分为几个部分:dispatch.reducer.state. 我们着重看下dispatch,该方法是Redux流程的第一步,在用户界面中通过

  • 在 React 中使用 Redux 解决的问题小结

    目录 在 React 中使用 Redux 解决的问题 在 React 项目中加入 Redux 的好处 React + Redux 安装 Redux React 中 Redux 的工作流程 React 计数器案例 使用 Redux Provide 组件 connect 方法 使用 bindActionCreators 方法继续简化 代码重构 为 Action 传递参数 Redux 弹出框 初始化静态内容 添加默认隐藏状态 定义操作按钮 衍生的问题 拆分合并 reducer 拆分 合并 调整组件 在

  • react.js框架Redux基础案例详解

    react.js框架Redux https://github.com/reactjs/redux 安装: npm install redux react-redux #基于react,我们在前面已经安装过了 Redux参考文档: http://redux.js.org/ Redux核心概念:Store 我们可以简单的理解为就是用来存储 各个组件的State或你自己定义的独立的state,对state进行统一读取.更新.监听等操作. http://redux.js.org/docs/basics/

  • Python Pandas基础操作详解

    目录 数据结构&Series: DataFrame的构建: 索引操作: DataFrame基本操作: 广播运算: 索引增删改查: 字符串元素处理: 数据规整: 总结 数据结构&Series: ''' series {索引 + 数据} 形式 索引是自动生成的 ''' #通过 list 创建 s1 = pd.Series([1, 2, 3, 4, 5]) #通过np数组创建 arr1 = np.arange(10) s2 = pd.Series(arr1) #自定义索引 s2 = pd.Ser

  • python字符串基础操作详解

    目录 字符串的赋值 单引号字符串赋值给变量 双引号字符串赋值给变量 三引号字符串赋值给变量(多行) 字符串的截取 截取指定位置的字符 获取指定位置之后的所有字符 截取指定位置之前的所有字符 获取所有的字符 获取指定倒数位置的字符,用[-]来进行表示 获取指定位置倒数之前的字符 获取两个位置之间的字符 字符串的基础使用方法 strip() lstrip() rstrip() lower() upper() capitalize() title() index() rindex() split()

  • Jquery基础之事件操作详解

    事件是用户操作时页面或页面加载时引发的用来完成javascript和HTML之间的交互操作.常见的元素点击事件.鼠标事件.键盘输入事件等,较传Javascript 相比JQuery增加并扩展了基本的事件处理机制,极大的增强了事件处理的能力. 一.DOM加载事件 页面加载完毕后浏览器会通过javascript为Dom元素加载事件,使用Javascript时候使用的是window.onload方法,而Jquery使用的是$(document).ready()方法,下表 展示两个事件的异同. wind

  • Node.js基础入门之缓存区与文件操作详解

    目录 缓存区 1. 什么是缓存区? 2. 创建指定长度的缓存区 3. 通过数组创建缓存区 4. 通过字符串创建缓存区 5. 读写缓存区 6. 复制缓存区 文件操作 1. 异步直接读取 2. 同步直接读取 3. 流式读取 4. 写入文件 5. 流式写入文件 6. 读取文件信息 7. 删除文件 8. 管道 9. 链式流 经过前面三天的学习,Node.js的基础知识已逐渐掌握,今天继续学习缓存区和文件操作,并稍加整理加以分享,如有不足之处,还请指正. 缓存区 1. 什么是缓存区? JavaScript

  • react redux及redux持久化示例详解

    目录 一.react-redux 二.redux持久化 一.react-redux react-redux依赖于redux工作. 运行安装命令:npm i react-redux: 使用: 将Provider套在入口组件处,并且将自己的store传进去: import FilmRouter from './FilmRouter/index' import {Provider} from 'react-redux' import store from './FilmRouter/views/red

  • React Redux使用配置详解

    目录 前言 redux三大原则 redux执行流程 redux具体使用 执行流程 redux使用流程 前言 在使用redux之前,首先了解一下redux到底是什么? 用过vue的肯定知道vuex,vuex是vue中全局状态管理工具,主要是用于解决各个组件和页面之间数据共享问题,对数据采用集中式管理,而且可以通过插件实现数据持久化 redux跟vuex类似,最主要的就是用作状态的管理,redux用一个单独的常量状态state来保存整个应用的状态,可以把它想象成数据库,用来保存项目应用中的公共数据

  • Git基础学习之tag标签操作详解

    目录 共享标签 推送本地的指定标签 推送本地所有为推送的标签 查看结果 删除标签 删除本地标签 删除远程标签 修改标签指定提交的代码 标签在.git目录中的位置 本文中所使用到的命令 共享标签 默认情况下,git push 命令并不会传送标签到远程仓库服务器上. 在创建完标签后,你必须显式地(手动)推送标签到远程服务器上. 需要将标签推送到远程版本库作为一个发行版本,可以通过以下两种方式: 推送本地的指定标签 这个过程就像共享远程分支一样,你可以执行命令: git push origin <ta

  • react装饰器与高阶组件及简单样式修改的操作详解

    使用装饰器调用 装饰器 用来装饰类的,可以增强类,在不修改类的内部的源码的同时,增强它的能力(属性或方法) 装饰器使用@函数名写法,对类进行装饰,目前在js中还是提案,使用需要配置相关兼容代码库. react脚手架创建的项目默认是不支持装饰器,需要手动安装相关模块和添加配置文件 安装相关模块 yarn add -D customize-cra react-app-rewired  @babel/plugin-proposal-decorators 修改package.json文件中scripts

随机推荐