React子组件中使用Redux

这个示例展示了如何在React应用中使用Redux来管理状态。`App.js`作为主要组件,从`store`订阅状态变化,并显示在页面上。`Son.js`和`Son2.js`作为子组件,同样订阅了`store`,并各自有增加和减少计数的按钮,通过调用`addAction`和`subAction`更新全局状态。

App.js

import React from 'react'; // 生成虚拟DOM
import store from "./store/store";
import {addAction, subAction} from "./store/action";
import Son from "./Components/Son";
import Son2 from "./Components/Son2";
import './App.css'

class App extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            count: store.getState().count // 获取数据
        }
    }
    componentDidMount() {
        store.subscribe(()=>{
            this.setState({
                count: store.getState().count
            })
        })
    }

    componentWillUnmount() {
        store.unsubscribe()
    }

    render(){
        return (
            <div>
                <p className='title'>React的子组件使用Redux</p>
                <p>{this.state.count}</p>
                <Son/>
                <Son2/>
            </div>
        )
    }
}
export default App; // 暴露给外界

Son.js

import React from 'react'; // 生成虚拟DOM
import store from "../store/store";
import {addAction, subAction} from "../store/action";
class Son extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            count: store.getState().count // 获取数据
        }
    }
    componentDidMount() {
        store.subscribe(()=>{
            this.setState({
                count: store.getState().count
            })
        })
    }

    componentWillUnmount() {
        store.unsubscribe()
    }

    render(){
        return (
            <div>
                <p>{this.state.count}</p>
                <button onClick={()=>{this.btnClick()}}>递增</button>
            </div>
        )
    }
    btnClick(){
        store.dispatch(addAction(1))
    }
}
export default Son; // 暴露给外界

Son2.js

import React from 'react'; // 生成虚拟DOM
import store from "../store/store";
import {addAction, subAction} from "../store/action";

class Son2 extends React.PureComponent {
    constructor(props) {
        super(props);
        this.state = {
            count: store.getState().count // 获取数据
        }
    }
    componentDidMount() {
        store.subscribe(()=>{
            this.setState({
                count: store.getState().count
            })
        })
    }

    componentWillUnmount() {
        store.unsubscribe()
    }

    render(){
        return (
            <div>
                <p>{this.state.count}</p>
                <button onClick={()=>{this.btnClick()}}>递减</button>
            </div>
        )
    }
    btnClick(){
        store.dispatch(subAction(1))
    }
}
export default Son2; // 暴露给外界
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值