旁观自己 善待朝夕|

猫老板的豆

园龄:9年4个月粉丝:52关注:0

📂react
🔖react
2022-04-26 17:50阅读: 1820评论: 0推荐: 0

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 全局数据进行操作。

超级简单 ~
超级舒服 ~

本文作者:猫老板的豆

本文链接:https://www.cnblogs.com/bingcola/p/16195817.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   猫老板的豆  阅读(1820)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 404 not found REOL
404 not found - REOL
00:00 / 00:00
An audio error has occurred.