react-redux 实现计数器

2023-11-12

1:首先编写action,描述要发生的行为,我们要做的是实现简单的加减,所以定义两种action,type字段就是描述这两种行为,最后暴漏这两种action

//定义action,主要用于描述将要发生的行为
const counterAddAction={
    type:'add'
};
const counterSubAction={
    type:'sub'
};

export {counterAddAction,counterSubAction}

2:定义reducer,处理行为操作,编写业务逻辑,而组件中只需要触发reducer即可

//定义reducer,用于处理发生的行为
const initialState={
    count:0,
    number:1
}
function counterReducer(state = initialState,action) {
    switch(action.type){
        case 'add':
                return  {
                    count: state.count + 1  //计数器加一
                };
        case 'sub':
            if(state.count > 0){
                return  {
                    count: state.count - 1  //计数器加一
                };
            }
        default:
            return state
    }
}
export default counterReducer;

3:定义组件

 

import React from 'react';
import {Component} from 'react';

class Counter extends Component{
    render(){
        console.log(this.props)
        const {count,counterAdd,counterSub }=this.props;
        
        return(
            <div>
                <button onClick={counterAdd}>点击加1</button>
                <button onClick={counterSub}>点击减一</button>
                <div>
                    <div>计数器值:{count}</div>
                </div>
            </div>
        )
    }

}
export default Counter;

4:将组件和state,action相关联

import Counter from './counter';
import {connect} from 'react-redux';
import {counterAddAction,counterSubAction} from '../store/action';
//这里引入组件Counter,引入action,引入connect

//将state映射到组件的props
const mapStateToProps=state=>{
    return{
        count:state.count
    }
}
//将action映射到组件的props
const mapDispatchToProps=dispatch=>{
    return{
        counterAdd:()=>{
            dispatch(counterAddAction)
        },
        counterSub:()=>{
            dispatch(counterSubAction)
        }
    }
}
//通过connect将组件和state关联起来,这样在组件中可以通过this.props来获取state
const CounterApp=connect(
    mapStateToProps,
    mapDispatchToProps
)(Counter)
export default CounterApp;

5:index引入 CounterApp,完成最后处理


import React from 'react';
import ReactDOM from 'react-dom';
import Counterapp from './component/CounterApp';
import {createStore} from 'redux';
import { Provider } from 'react-redux'
import Reducers from './store/reducer';
const store = createStore(Reducers)


ReactDOM.render(
    <Provider store={store}> 
        <Counterapp/>
    </Provider>, document.getElementById('root')
);

 

 

 

 

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

react-redux 实现计数器 的相关文章

随机推荐