3

在阅读 React/Redux 样板时,我遇到了以下代码片段

/components/auth/signout.js

import React, { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from '../../actions'
class Signout extends Component {

    componentWillMount() {
        this.props.signoutUser()
    }

    render() {
        return <div>Bye Bye</div>
    }
}

export default connect(null, actions)(Signout)

/actions/index/js

import axios from 'axios'
import { UNAUTH_USER, AUTH_USER, AUTH_ERROR, FETCH_MESSAGE } from './types'
const ROOT_URL = 'http://localhost:3090'

export function signoutUser() {
    localStorage.removeItem('token')
    return {
        type: UNAUTH_USER
    }
}

问题:有人可以解释为什么动作创建者signoutUser()只需type: UNAUTH_USER在被调用时返回动作对象,componentWillMount()并且该动作会神奇地被调度吗?

换句话说,我很困惑为什么没有dispatch调用,例如

dispatch(this.props.signoutUser())

或者

dispatch({ type: UNAUTH_USER })

redux 文档中所示。

4

2 回答 2

5
dispatch(this.props.signoutUser())

这就是 mapDispatchToProps 在幕后所做的。当您从使用 mapDispatchToProps 映射到您的组件的 signOutUser 返回值时,会发生以下情况

dispatch(/* returned value */)

我们实际上使用了很多速记,却不知道幕后发生了什么。例如,采取以下

const mapDispatchToProps = {
  signOutUser
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addTodo }, dispatch)
}

正如评论中所建议的,我认为您可以查看 mapDispatchToProps、bindActionCreators 实现,可以在以下链接中找到

https://github.com/reduxjs/react-redux/blob/3e53ff96ed10f71c21346f08823e503df724db35/src/connect/mapDispatchToProps.js

https://github.com/reduxjs/redux/blob/master/src/bindActionCreators.js

于 2018-09-26T15:03:14.630 回答
3

您可以通过多种方式使用 mapDispatchToProps 或调度功能

首先: 不提供 mapDispatchToProps

...
componentWillMount() {
    dispatch(signoutUser())
}
...
export default connect(null)(Signout);

在上述情况下,如果您不提供 mapDispatchToProps,则会将一个 dispatch prop 传递给您可以用来分派操作的连接组件。

其次:提供 mapDispatchToProps 作为函数

...
componentWillMount() {
    dispatch(signoutUser())
}
...
const mapDispatchToProps = (dispatch) => {
     return {
          signoutUser: () => dispatch(signoutUser)
     }
}
export default connect(null, mapDispatchToProps)(Signout);

在上述情况下,您将在 mapDispatchToProps 中调度操作,该操作将返回的值作为道具传递给组件

第三:提供一个对象作为 mapDispatchToProps

...
componentWillMount() {
    dispatch(signoutUser())
}
...
const mapDispatchToProps =  {
     return {
          signoutUser
     }
}

export default connect(null, mapDispatchToProps)(Signout);

上述情况是第二种情况的缩短版本,其中调度功能由 react-redux 内部处理

第三种情况是您间接使用的,因为当您导入操作时,例如

import * as actions from '../../actions';

actions基本上是作为 mapDispatchToProps 传递的对象

于 2018-09-26T15:21:58.443 回答