Redux之useSelector、useDispatch

React Redux 从 v7.1.0 开始支持 Hook API 并暴露了 useDispatchuseSelectorhook。以替代 Redux connect(),减少代码

  • useSelector 替代 mapStateToProps从store中提取state数据
  • useDispatch 替代 mapDispatchToProps从store中获取dispatch方法的引用

类组件connect(mapStateToProps, mapDispatchToProps)的使用方法:(传送门)

import {
    
     Component } from 'react';
import {
    
     connect } from 'react-redux';

class List extends Component {
    
    
    render() {
    
    
        return (
	        <div>
	            <label htmlFor="input">输入内容</label>
	            <input id="input" type="text" value={
    
    this.props.myValue} onChange={
    
    this.props.changeInput} />
	        </div>
        );
    }
}

// 把state数据映射到props中
// 这样在jsx中就可以用this.props.myValue来代替this.state.myValue获取值
const mapStateToProps = state => {
    
    
    return {
    
    
        myValue: state.myValue,
    };
};

// 把store.dispatch()挂载到props上
// 这样在jsx中就可以用this.props.changeInput来代替store.dispatch()改变store里的数据
const mapDispatchToProps = dispatch => {
    
    
    return {
    
    
        changeInput(e){
    
    
            const action = {
    
    
                type: 'change_input',
                value: e.target.value,
            };
            dispatch(action);
        }
    };
};

// List是 UI 组件,VisibleList 就是由 React-Redux 通过connect方法自动生成的容器组件。
export const VisibleList = connect(mapStateToProps, mapDispatchToProps)(List); 

函数式组件中利用 useSelectoruseDispatch等HooksApi替代connect(mapStateToProps, mapDispatchToProps)的使用方法:

import React from 'react';
import {
    
     useSelector, useDispatch } from 'react-redux';

export const List = () => {
    
    
    const myValue= useSelector(state => state.myValue); // 从store中提取state数据
    const dispatch = useDispatch(); // 从store中获取dispatch方法的引用
    const changeInput = (e) => {
    
    
        const action = {
    
    
            type: 'change_input',
            value: e.target.value,
        };
        dispatch(action);
    }

    return (
        <div>
            <label htmlFor="input">输入内容</label>
            <input id="input" type="text" value={
    
    myValue} onChange={
    
    changeInput} />
        </div>
    );
}

不用写一堆繁琐的 connectmapStateToPropsmapDispatchToProps 了,直接使用 hook函数 对 redux 全局数据进行操作。

超级简单 ~
超级舒服 ~

猜你喜欢

转载自blog.csdn.net/x550392236/article/details/124431195
今日推荐