react学习——28react-redux实现多组件共享数据(精简版)

1、目录结构

2、containers/Count/index.js

javascript 复制代码
import {createIncrementAction, createDecrementAction, createIncrementAsyncAction} from '../../redux/action/count'
//引入conect用于链接UI组件与redux
import {connect} from 'react-redux'
import React, {Component} from "react";
class Count extends Component {
    //加法
    increment=()=>{
        const {value} = this.selectNum
        this.props.jia(Number(value))
    }
    //减法
    decrement=()=>{
        const {value} = this.selectNum
        this.props.jian(Number(value))
    }
    //奇数加
    incrementIfOdd=()=>{
        const {value} = this.selectNum
        const {count} = this.props
        if(count%2!==0) {
            this.props.jia(Number(value))
        }
    }
    //异步加
    incrementAsync=()=>{
        const {value} = this.selectNum
        this.props.jiaAsync(Number(value),500)
    }
    render()
    {
        console.log('UI组件接收到的props是',this.props)
        return(
            <div>
                <h1>Coun组件</h1>
                <h4>当前求和为:{this.props.count},下方总人数为:{this.props.personNum}</h4>
                <select ref={(c)=>this.selectNum=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>
        );
    }
}
//使用connect()()创建
export default connect(
    state=>({count:state.count,personNum:state.persons.length}),
    {
        jia:createIncrementAction,
        jian:createDecrementAction,
        jiaAsync:createIncrementAsyncAction
    }
)(Count)

containers/Person/index.js

javascript 复制代码
import React, {Component} from "react";
import {connect} from 'react-redux'
//引入personACTion
import {createAddPersonAction} from '../../redux/action/person'
//引入nanoid
import {nanoid} from 'nanoid';
class Person extends Component {
    addPerson=()=> {
        const name=this.nameNode.value;
        const age=this.ageNode.value;
        const personObj={id:nanoid(),name,age};
        console.log(personObj);
        this.props.createAddPersonAction(personObj)
        this.nameNode.value='';
        this.ageNode.value='';
    }
    render()
    {
        return(
            <div>
                <h1>我是Peson组件,上方求和为:{this.props.sum}</h1>
               <input ref={c=>this.nameNode=c} type='text' placeholder='输入姓名' />
                &nbsp;
                <input ref={c=>this.ageNode=c} type='text' placeholder='输入年龄'/>
                &nbsp;
                &nbsp;
                &nbsp;
                <button onClick={this.addPerson}>添加</button>
                <ul>
                    {
                        this.props.persons.map(item=>{
                            return <li key={item.id}>{item.name}---{item.age}</li>
                        })
                    }
                </ul>
            </div>
        );
    }
}
export default connect(
    state=>({persons:state.persons,sum:state.count}),
    {
        createAddPersonAction
    }
)(Person)

3、redux/action/count.js

javascript 复制代码
/*
    该文件专门为Count组件生成action对象
 */
import {INCREMENT,DECREMENT} from '../constant'
import store from "../store";
// function createIncrementAction(data){
//     return {type:'increment',data}
// }
export const createIncrementAction = data=>({type:INCREMENT,data})
// function createDecrementAction(data){
//     return {type:'decrement',data}
// }
//同步action,就是形参为data,返回值为action对象
export const createDecrementAction = data=>({type:DECREMENT,data})

// export default {
//     createIncrementAction,
//     createDecrementAction
// }
//所谓的异步action,就是指action的值为函数,异步action中一般都会调用同步action,异步action不是必须要用的
export const createIncrementAsyncAction = (data,time)=>{
    return ()=>{
        setTimeout(()=>{
            //通知redux
            store.dispatch(createIncrementAction(data))
        },time)
    }
}

redux/action/person.js

javascript 复制代码
//引入常量
import {ADD_PERSON} from '../constant'
//创建一个添加person的action
export const createAddPersonAction = personObj=> {
    return {type:ADD_PERSON,data:personObj}
}

redux/reducers/count.js

javascript 复制代码
/*
    1.该文件是用于创建一个为count服务的reducer,reducer的本质就是一个函数
    2.reducer函数会接到两个参数,分别为:之前的状态(preState),动作对象(action)
*/
import {INCREMENT,DECREMENT} from "../constant";
const initState = 0
export default function countReducer(preState=initState,action) {
    console.log('countReducer',preState,action)
    const {type,data} = action
    // 根据type决定如何加工数据
    switch (type){
        case INCREMENT:
            console.log('@')
            return preState + data
        case DECREMENT:
            return preState - data
        default:
            return preState
    }
}

redux/reducers/person.js

javascript 复制代码
//引入常量
import {ADD_PERSON} from '../constant'
//初始化state
const initState=[{
    id:1,
    name:'Tom',
    age:18
}]

export default function personReducer(preState=initState,action){
    const {type,data} = action
    switch (type){
        case ADD_PERSON:
            return [data,...preState]
        default:
            return preState
    }
}

redux/constant.js

javascript 复制代码
/*
    该模块用于定义状态管理的常量名称,目的只有一个:便于管理的同时,防止程序员单词拼写错误
*/
export const INCREMENT = 'increment'
export const DECREMENT = 'decrement'
export const ADD_PERSON = 'add_person'

redux/store,js

javascript 复制代码
/*
    该文件专门用于创建一个为Count组件服务的store对象
 */
//引入createStore,专门创建redux中最为核心的store对象
import {createStore,applyMiddleware,combineReducers} from 'redux'
//引入cunter.redux.js文件
import countReducer from './reducers/count'
//引入personReducer文件
import personReducer from './reducers/person'
//引入redux-thunk用于支持异步action
import {thunk} from 'redux-thunk'
//引入redux-devtools-extension
import {composeWithDevTools} from 'redux-devtools-extension'
//汇总所有reducer
const allReducer = combineReducers({
    count:countReducer,
    persons:personReducer
})
//暴露store applyMiddleware(thunk)
export default createStore(allReducer,composeWithDevTools(applyMiddleware(thunk)))

4、src/App.js

javascript 复制代码
import React, {Component} from "react";
import Count from "./containers/Count";
import Person from "./containers/Person";
//引入store
// import store from "./redux/store";
export default class App extends Component {
    render()
    {
        return(
            <div>
                <Count></Count>
                <hr/>
                <Person></Person>
            </div>
        );
    }
}

src/index.js

javascript 复制代码
import React from "react";
import ReactDOM from 'react-dom'
import App from './App'
import store from './redux/store'
import {Provider} from "react-redux";

ReactDOM.render(
    <Provider store={store}>
        <App/>
    </Provider>,
    document.getElementById('root'))
相关推荐
anyup_前端梦工厂1 小时前
初始 ShellJS:一个 Node.js 命令行工具集合
前端·javascript·node.js
mashagua1 小时前
RPA系列-uipath 学习笔记3
笔记·学习·rpa
5hand1 小时前
Element-ui的使用教程 基于HBuilder X
前端·javascript·vue.js·elementui
GDAL1 小时前
vue3入门教程:ref能否完全替代reactive?
前端·javascript·vue.js
六卿1 小时前
react防止页面崩溃
前端·react.js·前端框架
沐泽Mu1 小时前
嵌入式学习-QT-Day05
开发语言·c++·qt·学习
锦亦之22332 小时前
cesium入门学习二
学习·html
z千鑫2 小时前
【前端】详解前端三大主流框架:React、Vue与Angular的比较与选择
前端·vue.js·react.js
m0_748256142 小时前
前端 MYTED单篇TED词汇学习功能优化
前端·学习
IT古董3 小时前
【机器学习】机器学习的基本分类-半监督学习(Semi-supervised Learning)
学习·机器学习·分类·半监督学习