React-Redux:在 React 组件中使用动作创建器

Posted

技术标签:

【中文标题】React-Redux:在 React 组件中使用动作创建器【英文标题】:React-Redux: Using action creators in React components 【发布时间】:2019-07-08 19:58:05 【问题描述】:

我是 React/Redux 的新手,感谢您的帮助。我正在参加有关此主题的 Udemy 课程。课程讲师创建这样的组件。

import React,  Component  from 'react';
import  connect  from 'react-redux';

import  fetchUser  from '../actions';

class User extends Component 
    componentDidMount()
        this.props.fetchUser(this.props.userId);
    

    render()
        const  user  = this.props;

        if(!user) return null;

        return(
            <div className="header"> User Info: user.name</div>
        );
    


const mapStateToProps = (state, ownProps) => 
    return  user: state.users.find( user => user.id === ownProps.userId);
;

export default connect(mapStateToProps,  fetchUser )(User)

我的问题:为什么在componentDidMount() 中他在fetchUsers() 前面加上this.props? 并非他将fetchUsers() 作为来自父组件的道具传递。这就是父级使用这个组件的方式&lt;User userId=post.userId/&gt;

注意:此代码有效

【问题讨论】:

【参考方案1】:

正是因为这一行:

export default connect(mapStateToProps, fetchUser )(User)

connect 的第二个参数叫做mapDispatchToProps,它将动作添加到道具中

来自docs:

connect 可以接受一个名为 mapDispatchToProps 的参数,它允许 您创建在调用时调度的函数,并传递那些 用作组件的道具。

const mapDispatchToProps = dispatch => 
  return 
    // dispatching plain actions
    increment: () => dispatch( type: 'INCREMENT' ),
    decrement: () => dispatch( type: 'DECREMENT' ),
    reset: () => dispatch( type: 'RESET' )
  

您的代码使用“对象速记”形式。

【讨论】:

【参考方案2】:

示例中的mapDispatchToProps 是简写方式。如果它是这样写的,可能会更容易判断发生了什么:

import React,  Component  from 'react';
import  connect  from 'react-redux';

import  fetchUser  from '../actions';

class User extends Component 
    componentDidMount()
        this.props.fetchUser(this.props.userId);
    

    render()
        const  user  = this.props;

        if(!user) return null;

        return(
            <div className="header"> User Info: user.name</div>
        );
    


const mapStateToProps = (state, ownProps) => 
    return  user: state.users.find( user => user.id === ownProps.userId);
;

const mapDispatchToProps = () => (
  fetchUser
);

export default connect(mapStateToProps, mapDispatchToProps)(User)

也许这显示得更清楚,但调度函数 (fetchUser) 正在映射到组件属性。就像状态值(用户)被映射到组件的属性一样。我认为您只是因为使用了速记而感到困惑。

【讨论】:

我同意以这种方式查看它更简单,但实际上你可以只做const mapDispatchToProps = fetchUser ,这就是你需要做的全部

以上是关于React-Redux:在 React 组件中使用动作创建器的主要内容,如果未能解决你的问题,请参考以下文章

使用通过 react、redux 和 react-redux 完成的组件以及在 react 应用程序中使用 webpack 构建时出错

React-Redux 中同一组件的多个实例

如何在类组件中使用 react-redux useSelector?

如何使用 react-redux 钩子测试组件?

使用 react-routerv4 从 react-redux 应用程序中的状态渲染组件时出现 404 错误?

react-redux