【问题标题】:React-Redux: Using action creators in React componentsReact-Redux:在 React 组件中使用动作创建器
【发布时间】: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;

注意:此代码有效

【问题讨论】:

    标签: reactjs redux react-redux


    【解决方案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 },这就是你需要做的全部
      猜你喜欢
      • 1970-01-01
      • 2018-10-22
      • 2020-12-05
      • 1970-01-01
      • 2020-11-24
      • 1970-01-01
      • 2017-08-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多