【React】使用react-redux编写counter应用(优化后)

继续根据上一篇博文中提出的问题进行优化:https://blog.csdn.net/zqq_2016/article/details/109227761

1. 下载依赖包

cnpm i --save redux react-redux

cnpm i --save redux-thunk  //redux插件(异步中间价),用来写异步代码

2. action-types.js

/*
 * 包含所有的action type的常量字符串
 */
export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'

3. reducers.js

import {DECREMENT, INCREMENT} from "../redux_counter_u/action-types";

export function counter(state = 0, action) {
    switch (action.type) {
        case INCREMENT:
            return state + action.data
        case DECREMENT:
            return state - action.data
        default:
            return state
    }
}

4. actions.js

import {DECREMENT, INCREMENT} from "../redux_counter_u/action-types";
//增加
export const increment = number => ({
    type: INCREMENT,
    data: number
})
//减少
export const decrement = number => ({
    type: DECREMENT,
    data: number
})
//异步(返回一个函数)
export const incrementAsync = number => {
    return dispatch => {
        // 异步代码
        setTimeout(() => {
            // 1s后才去分发一个增加的action
            dispatch(increment(number))
        }, 1000)
    }
}

5. store.js

import {createStore, applyMiddleware} from "redux";
import {counter} from './reducers'
import thunk from 'redux-thunk'

const store = createStore(counter, applyMiddleware(thunk)) //应用上异步中间件

export default store

6. containers/app.js

import Counter from "../components/react_ui/react_redux_counter/counter";
import {connect} from 'react-redux'
import {increment, decrement, incrementAsync} from "../redux/react_redux_counter_u/actions";

export default connect(
    state => ({count: state}),
    {increment, decrement, incrementAsync}
)(Counter)

7. components/react_ui/react_redux_conter/counter.js

import React, {Component} from 'react';
import PropTypes from "prop-types";

class Counter extends Component {
    // 接收3个属性
    static propTypes = {
        count: PropTypes.number.isRequired,
        increment: PropTypes.func.isRequired,
        decrement: PropTypes.func.isRequired,
        incrementAsync: PropTypes.func.isRequired
    }
    // 增加
    increment = () => {
        const number = this.select.value * 1
        // const {count} = this.state
        // this.setState({count: count + number})
        // 调用store的方法更新状态
        this.props.increment(number)
    }
    // 减少
    decrement = () => {
        const number = this.select.value * 1
        // const count = this.props.store.getState()
        // this.setState({count: count - number})
        this.props.decrement(number)
    }
    // 偶数增加(满足条件后再增加)
    incrementIfOdd = () => {
        const number = this.select.value * 1
        const {count} = this.props
        if (count % 2 === 1) {
            // this.setState({count: count + number})
            this.props.increment(number)
        } else {
            alert(`${count}不是奇数呦!`)
        }
    }

    // 异步增加(设置延时定时器)
    incrementAsync = () => {
        const number = this.select.value * 1
        this.props.incrementAsync(number)
    }

    render() {
        // const {count} = this.state
        // 得到原本的count状态
        const {count} = this.props
        console.log("App", count)
        return (
            <div>
                <p>click {count} times</p>
                <div>
                    <select ref={select => this.select = select}>
                        <option value="1">1</option>
                        <option value="2">2</option>
                        <option value="3">3</option>
                    </select>
                    <button onClick={this.increment}>+</button>
                    <button onClick={this.decrement}>-</button>
                    <button onClick={this.incrementIfOdd}>increment if odd</button>
                    <button onClick={this.incrementAsync}>increment async</button>
                </div>
            </div>
        );
    }
}

export default Counter;

8. index.js

import React from 'react';
import ReactDOM from 'react-dom';
import App from '../src/containers/app'
import {Provider} from 'react-redux';
import store from "./redux/react_redux_counter_u/store";

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

9. 效果图

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
最新版的 react-redux 使用方法如下: 首先,确保你的项目已经安装了 react-redux 依赖包。你可以使用以下命令安装它: ``` npm install react-redux ``` 或 ``` yarn add react-redux ``` 接下来,你需要创建一个 Redux store。你可以使用 Redux Toolkit 来简化这个过程。首先,导入 `configureStore` 和 `getDefaultMiddleware` 函数: ``` import { configureStore, getDefaultMiddleware } from '@reduxjs/toolkit'; ``` 然后,创建一个 rootReducer 来合并你的所有 reducer: ``` import { combineReducers } from 'redux'; const rootReducer = combineReducers({ // 这里是你的 reducer }); ``` 接着,使用 `configureStore` 函数创建 Redux store。你可以通过传入一个对象来配置 store,例如指定 reducer、middleware 等等。以下是一个示例: ``` const store = configureStore({ reducer: rootReducer, middleware: getDefaultMiddleware() }); ``` 现在,你可以使用 `<Provider>` 组件来将 Redux store 提供给你的整个应用程序。在你的根组件中,导入 `<Provider>` 组件和你的 Redux store,然后将其包裹在应用的最外层: ``` import { Provider } from 'react-redux'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') ); ``` 通过将 Redux store 提供给整个应用程序,你可以在应用的任何地方使用 `useSelector` 和 `useDispatch` 钩子来访问 Redux store 中的状态和分发 action。例如,在你的组件中,你可以这样使用: ``` import { useSelector, useDispatch } from 'react-redux'; const MyComponent = () => { const counter = useSelector(state => state.counter); const dispatch = useDispatch(); // 使用 counter 和 dispatch }; ``` 这就是最新版的 react-redux使用方法。你可以根据你的具体需求,自定义配置和使用其他相关的 react-redux API。希望对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zqq_2016

有用的话,来打赏博主吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值