在react中使用redux && react-redux的使用demo

前言:

redux是一种状态管理工具,可以存储和操作一些全局或者很多组件需要使用的公共数据。

平心而论,redux的使用对于新上手来说不太友好,多个依赖包的,多种api的结合使用,相对来说比做同样一件事的vuex用起来比较麻烦.不过,熟能生巧,用多了也就习惯了,下面是个人的一个demo,是自己根据尚硅谷张天禹react教程学习的,然后写的demo.

这个demo是一个实用版本的demo,而不是深入研究redux本身的各种api操作

思路和准备:

需要的依赖包:

redux : 状态管理的核心插件(不仅仅是在react中能用,也可以在vue中用,但很显然,vue不需要 !--)

react-redux : 专门让redux和react之间对接的一个插件,让redux写起来没有那么的麻烦,(相对没有)

redux-devtools-extension : 调试工具,类似于vue-devtools,方便调试和查看,(当然了,本人是console.log党,用得少,配置上就行了)

redux-thunk: 可以让redux的值进行异步的修改,比较重要,能节省不少东西

思路:

首先,先要创建一个store,store是每个组件访问的核心,就像淘宝网站一样.

然后每个网站里面都有自己的商店,不同的商店对应不同的商品和购买方式,所以你就需要针对具体的数据类型,配置具体操作他的方法.

然后每个组件就像消费者一样,可以直接访问淘宝网站和站内所有的店铺,并且可以选取你希望他方式购买他,并且你的消费对其他客户也会造成影响,比如这件商品只剩一件了,你买了,其他用户就没货了,这也就是全局数据状态共享的意义.

ok了.学会了这些,那就直接展示代码了,感觉条例还是比较清晰的.

文件结构

|-- src(业务文件夹)        ---------------互联网世界

    |--pages(普通组件文件夹)    --------------电商领域     

        |--index.jsx(demo父组件)    --------------消费者集合

        |--demo1.jsx(子组件1)   --------------消费者1

        |--demo2.jsx(子组件2)   --------------消费者2

    |--redux(redux文件夹)

        |--actions(修改demo1数据状态的操作函数集合)  ------------消费者购物方式集合

            |--demo1Actions.js(demo1数据操作方法)     -------------京东支付,选择加急,使用京豆

            |--demo2Actions.js(demo2数据操作方法)     -------------微信支付,不着急,坐等快递

        |--reducers(全局状态初始化和操作分发的集合)  

            |--demo1.js(demo1的数据)  -------------网店1

            |--demo2.js(demo2的数据)  -------------网店2

            |--index.js(全局数据集合)  --------------网店集合

        |--store.js(全局数据的载体)   ---------------电商网站

|--App.jsx(根组件) 

|--main.jsx(项目入口组件)   ---------------互联网

大概就是这么一个比喻,希望看客老爷们能理解我的这种比喻

某位大佬创建了一个电商网站,叫做四道(store).store里面可以创建很多网店,这些网店叫做瑞丢瑟斯(reducers).现在两个消费者,戴某1和戴某2,有两个店铺叫做demo1和demo2.

戴某1看上了demo1店铺的一件商品,情侣表,这个商品只有2件了,然后demo1就买了他,他将这个商品的接收地址分别发给了他自己和他对象那里,这个怎么买是他自己决定的,这个操作就是艾克神(action).因为戴某1买了这两件件商品,demo1店铺里面就没有这两件商品了.等到戴某2也想买这件商品的时候,发现这件商品已经空了.所以,店铺练得商品就是全局的数据or状态.

ok了,上具体代码:

代码

redux/store.js
// store构建方法
import {legacy_createStore,applyMiddleware} from 'redux'

// 支持异步
import thunk from 'redux-thunk'

// 开发工具
import {composeWithDevTools} from 'redux-devtools-extension'

// 所有的reducers
import reducer from './reducers'

// 将这些方法和参数组合,形成一个全局的store,store也是redux的核心
export default legacy_createStore(reducer,composeWithDevTools(applyMiddleware(thunk)))
main.js
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import 'reset-css'
import './index.css'
import store from './redux/store.js'
import {Provider} from 'react-redux'

ReactDOM.createRoot(document.getElementById('root')).render(
  // 
  
    
  
    
  // ,
)
redux/reducers/index.js
import {combineReducers} from 'redux'
import demo1 from './demo1'
import demo2 from './demo2'


//将会在store上暴露的模块
export default combineReducers({
    demo1,
    demo2
})
redux/reducers/demo1.js
const initValue = 0
export default function demo1(value = initValue,action){
    console.log(action,'点击了')
 const {type,data} = action
 switch(type){
    case 'add':
        return value+data;
    case 'delete':
        return value-data;
    default:
        return value
 }
}
redux/reducers/demo2.js
//初始化的值
const initValue = {
    name:'王惊涛',
    age:27
}

export default function demo2(value=initValue,action){
const {type,data} = action
switch(type){
  case 'change':
    return data
  default:
    return value
}
}
redux/actions/demo1Actions.js
export const addAction = data => ({type:'add',data})
export const deleteAction = data => ({type:'delete',data})
export const asyncAddAction = (data,time) => {
    return (dispatch)=>{
        setTimeout(()=>{
            dispatch(addAction(data))
        },time)
    }
} 
redux/actions/demo2Actions.js
export const changeData = data => ({type:'change',data})
src/pages/index.jsx
import React, { Component } from 'react'
import withRouter from '../../utils/withRouter'
import Demo1 from './demo1'
import Demo2 from './demo2'
export default  withRouter(class index extends Component {
  render() {
    return (
      

) } })
src/pages/demo1.jsx
import React, { Component } from 'react'
import withRouter from '../../utils/withRouter'
import {connect} from 'react-redux'
import {addAction,deleteAction} from '../../redux/actions/demo1Actions'
import {Button} from 'antd'
const Demo1 =  withRouter(class index extends Component {
    addValue = ()=>{
      this.props.addAction(1)
    }
    deleteValue = ()=>{
      this.props.deleteAction(1)
    }
  render() {
    console.log(this.props,'this.props---')
    return (
      

demo1页面

原始操作值:{this.props.demo1}


demo2里面的内容:---- 姓名:{this.props.demo2.name} 年龄:{this.props.demo2.age}

) } }) export default connect( state =>({ demo1:state.demo1, demo2:state.demo2 }), {addAction,deleteAction} )(Demo1)
src/pages/demo2.jsx
import React, { Component } from 'react'
import withRouter from '../../utils/withRouter'
import { connect } from 'react-redux'
import {changeData} from '../../redux/actions/demo2Actions'
import {addAction} from '../../redux/actions/demo1Actions'
import {Input,Button} from 'antd'
const Demo2 = withRouter( class index extends Component {
    state = {
        data:null
    }
    InputStype = {
      width:'400px'
    }
    componentDidMount(){
      console.log(this.props,'demo2中的props值')
        this.setState({
            data:this.props.demo2
        },()=>{
            console.log(this.props,'this.props---demo2???')
        })
    }
    changeData = ()=>{
      this.props.changeData({
        name:'马师',
        age:28
      })
    }
    addHandler = ()=>{
      this.props.addAction(1)
    }
  render() {
    return (
      

demo2页面

姓名:{this.props.demo2.name}

年龄:{this.props.demo2.age}


demo1里面的值:{this.props.demo1}

) } }) export default connect( state=>({ demo1:state.demo1, demo2:state.demo2 }), {changeData,addAction} )(Demo2)
withRouter.jsx
import {
    useLocation,
    useNavigate,
    useParams,
  } from "react-router-dom";
  
  function withRouter(Component) {
    function ComponentWithRouterProp(props) {
      let location = useLocation();
      let navigate = useNavigate();
      let params = useParams();
      return (
        
      );
    }
  
    return ComponentWithRouterProp;
  }

  export default withRouter

感觉有用的就给个赞吧,谢啦!

你可能感兴趣的:(react,react.js)