一文搞懂redux在react中的初步用法

来自:网络
时间:2021-06-09
阅读:

Redux是一个数据状态管理插件,当使用React或是vue开发组件化的SPA程序时,组件之间共享信息是一个非常大的问题。例如,用户登陆之后客户端会存储用户信息(ID,头像等),而系统的很多组件都会用到这些信息,当使用这些信息的时候,每次都重新获取一遍,这样会非常的麻烦,因此每个系统都需要一个管理多组件使用的公共信息的功能,这就是redux的作用。

如果你是从来没有接触过redux的开发者,希望您能够有耐心的看一看,我也是看好很多博客慢慢自己总结的!!!!比大佬们一个一个分布找要强一点。

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

//Class引入
import { connect } from 'react-redux';

//Hook引入
import { useSelector, useDispatch } from 'react-redux'

import { add, clear } from '../../redux/actions/count';


//hook 展示组件
const CountItem = (props) => {
    // 解构出来
    const {
        count,
        flag,
        add,
        clear
    } = props
    return (
        <>
            <h2>当前求和为:{count}</h2>
            <h3>当前Flag:{flag ? 'true' : 'false'}</h3>
            <button onClick={add}>点击+1</button>
            <button onClick={clear}>清零</button>
        </>
    )
}

//hook 容器组件
const Count = () => {
    const count = useSelector(state => state.sum)
    const flag = useSelector(state => state.flag)
    const dispatch = useDispatch()

    const countAdd = () => {
        console.log(add.type)
        dispatch(add(1))
    }

    const clearNum = () => {
        dispatch(clear())
    }

    return <CountItem count={count} flag={flag} add={countAdd} clear={clearNum}  />
}

export default Count



// class 展示组件
// class Count extends Component {
//     add = () => {
//         // 通知redux
//         this.props.add(1);
//     };
//     clear = () => {
//         this.props.clear();
//     };
//     render() {
//         return (
//             <Fragment>
//                 <h2>当前求和为:{this.props.count}</h2>
//                 <h3>当前Flag:{this.props.flag ? 'true' : 'false'}</h3>
//                 <button onClick={this.add}>点击+1</button>
//                 <button onClick={this.clear}>清零</button>
//             </Fragment>
//         );
//     }
// }

// class 容器组件
// export default connect(
//     // 1.状态
//     state => ({ count: state.sum, flag: state.flagState }),
//     // 2.方法
//     { add, clear }
// )(Count);

基本的使用差不多就是这个样子,我们在hook上面用到的关键方法就是useSelector来使用redux的state、用dispatch来调用reduce;在class组件中用connect进行state和方法(reduce)的关联。

这里面难点就在于reduce和state

这里的reduce是什么

上面的代码里面我们用到了add和clear这两个方法,我们新建一个js文件来实现这两个方法。

// 为Count组件创建action对象
// 引入常量
import { ADD, CLEAR } from '../constant';

// 创建加一action对象的函数
export const add = data => ({
    type: ADD,
    data,
});

// 创建清零action对象的函数
export const clear = data => ({
    type: CLEAR,
    data,
});

上面有常量----这是为了方便actionType的统一管理,创建对应的action对象有助于代码模块化。
贴上,自己建一个constant.js放进去

export const ADD = 'add';
export const CLEAR = 'clear';

到这里我们的action对象定义的差不多了,我们要进行reducer的管理了。也就是dispatch分发上面的action对象来实现state的更新

在reducer文件夹里面我们定义一个count.js

// 为Count组件创建一个reducer
// reducer接收两个参数:之前状态的preState,动作对象action

import { ADD, CLEAR } from '../constant.js';

// 设定初始状态
const initState = 0;

export default function addReducer(preState = initState, action) {
    // 从action中获取type和data
    const { type, data } = action;
    // 根据type决定如何加工数据
    switch (type) {
        case ADD:
            return preState + data;
        case CLEAR:
            return 0;
        // 初始化动作
        default:
            return preState;
    }
}

上面的方法要通过dispatch来进行type的分发调用(强调加一)

到这里使用就完成了 接下来看配置redux到react项目中

这里就不要倒叙了,因为这里倒叙不合理。
这里关键的几个配置
store.js的配置和全局的store的使用

先看全局使用store
在你的根路由下面用Provider包裹App。

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.jsx';
import store from './redux/store';
import { Provider } from 'react-redux';

ReactDOM.render(
    // Provider包裹App,目的:让App所有的后代容器组件都能接收到store
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);

这里面有个redux/store.js 看代码

// 整个文档只有一个store对象,createStore接收两个参数,第一个是state树,第二个是要处理的action
//applyMiddleware 汇总所有的中间件变成一个数组依次执行,异步处理
import { createStore, applyMiddleware } from 'redux';
//中间件
import thunk from 'redux-thunk';
//汇总所有的reducer
import allReducers from './reducers/index';
//这里是goole的调试调试工具,具体使用:百度
import { composeWithDevTools } from 'redux-devtools-extension';

// 暴露store
export default createStore(allReducers, composeWithDevTools(applyMiddleware(thunk)));

到这里这篇文章就要结束了,里面的一些执行流程和原理我还不是理解,接下来仍要多多巩固,多多学习。

以上就是一文解决redux在react中的初步使用的详细内容,更多关于redux在react中使用的资料请关注其它相关文章!

返回顶部
顶部