redux的简单使用

需要在react中注入store,一般是在App根组件中,注入方式是 store={store}

import store from './store/index'

<Provider store={store}>
	<App />
</Provider>

src\store\counter

// src\store\counter\index.jsx
export const counterReducer = (state = { counter: 0 }, action) => {
  if (action.type === 'increment') {
    return { counter: state.counter + 1 };
  }
  if (action.type === 'decrement') {
    return { counter: state.counter - 1 };
  }
  if (action.type === 'reset' && action.name === 'counterReducer') {
    return { counter: 0 };
  }
  return state;
};

src\store\index.jsx

createStore 官方已经不建议使用,所以改成了使用configureStore,需要下载才可以使用

 npm install --save @reduxjs/toolkit
// import { createStore } from "redux";
import { configureStore } from '@reduxjs/toolkit';
import reducer from './reducer';

// 引入总模块
const store = configureStore({ reducer });
export default store;

src\store\reducer.jsx

// src\store\reducer.jsx
import { combineReducers } from "redux";
import { counterReducer } from "./counter/index";

// 模块化
const reducer = combineReducers({
    Num: counterReducer,
});

export default reducer;

src\pages\reduxTest\index.jsx

import { Button } from "antd";
import { useSelector, useDispatch } from "react-redux";

const Counter = () => {
    const dispatch = useDispatch();

    const counter = useSelector((state) => { return state.Num.counter });

    const incrementHandler = () => {
        dispatch({ type: "increment", name: "counterReducer" });
    };
    const decrementHandler = () => {
        dispatch({ type: "decrement", name: "counterReducer" });
    };

    const toggleCounterHandler = () => {
        dispatch({ type: "reset", name: "counterReducer" })
    };


    return (
        <main >
            <h1>Redux Counter</h1>
            <div>{counter}</div>
            <Button type="primary" onClick={incrementHandler}>1</Button>
            <Button type="primary" onClick={decrementHandler}>1</Button>
            <Button type="primary" onClick={toggleCounterHandler}>Toggle Counter</Button>
        </main>
    );
};
export default Counter;

不记得这个代码参考了谁的了,如有雷同,求放过/(ㄒoㄒ)/~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值