Hooks的useSelector、useDispatch的出现和基本使用

官方文档介绍:
React Redux 从 v7.1.0 开始暴露了 useDispatch 和 useSelector 等 hookAPI。以替代 Redux connect(),减少Redux在使用connect(mapStateToProps, mapDispatchToProps)代码量:

1.之前旧版本的class类式组件用法

import React,{ Component } from "react";
import { connect } from "react-redux";

interface Iprops{
    name: string,
    changeNameDispatch:Function
}

class Myname extends Component {
    onDispatch() {
        this.props.changeNameDispatch('老王')
    }

    render() {
        return 

展示name:{this.props.name}

} } // 把state数据映射到props中 在当前组件中的props属性就可以访问到name //这个是在dva中有namespace模块名myBox 正常使用state.name即可 const mapStateToProps = (state:any) => { return { name: state.myBox.name, }; }; // 把store.dispatch()挂载到props上 // 在组件中就可以用this.props.changeNameDispatch来代替store.dispatch()改变store里的数据 const mapDispatchToProps = (dispatch:Function) => { return { changeNameDispatch(val:string){ const action = { type: 'changeName', payload: val, }; dispatch(action); } }; }; export default connect(mapStateToProps,mapDispatchToProps)(Myname);

2.使用新的Hooks useSelector、useDispatch等替换以上的connect(mapStateToProps, mapDispatchToProps)方式:

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

interface Iprops{
    name: string,
    changeNameDispatch:Function
}
const Myname: React.FC = (props) => {
    const dispatch = useDispatch();
    const state = useSelector(state => state);

    const onDispatch = () => {
        const action = {
            type: 'changeName',
            payload: '老王',
        };
        dispatch(action);
    }
    
    return (

展示name:{state.myBox.name}

) } export default Myname;

你可能感兴趣的:(react,react.js)