在没有 Dispatch 功能的情况下对 React 使用操作是否正确?

Using actions on React without a Dispatch function is correct?

我正在 React 上实现 Redux,它目前正在运行,但我不确定它是否正确。我有一个包含 3 个文件的 redux 文件夹:actions、reducers 和 store。

A​​ctions 有这个代码:

export const SETTER_USER = "SETTER_USER"

export const setterUserAction = ({ email, username, role, lastVideo }) => ({
  type: SETTER_USER,
  payload: { email, username, role, lastVideo }
})

我正在从组件中调用此操作,这是组件上的代码:

import React, { useState, useEffect } from "react";
import { connect } from 'react-redux'
import { setterUserAction } from '../../redux/actions'
...

const Login = ({ navigation, user, setUser }) => {
...
}

const mapStateToProps = state => ({
  user: state.user
})

const mapDispatchToProps = ({
  setUser: setterUserAction
})

export default connect(mapStateToProps, mapDispatchToProps)(Login)

我以前是把action放在组件里面的,我想是不是很理想。所以我把它移到了 actions.js 文件中。但是现在我没有使用调度函数,这感觉很奇怪,因为调度是整个模式的一部分。所以你怎么看?这是否正确实施?还是全凭运气?

您正在将 mapDispatchToProps 定义为一个对象。它是由 react-redux 团队推荐的:您可以在此处阅读更多相关信息:https://react-redux.js.org/using-react-redux/connect-mapdispatch#defining-mapdispatchtoprops-as-an-object

We recommend always using the “object shorthand” form of mapDispatchToProps, unless you have a specific reason to customize the dispatching behavior.

Update:如果你使用带 Hook 的函数组件,你应该使用 React-Redux hooks API:https://react-redux.js.org/api/hooks

We recommend using the React-Redux hooks API as the default approach in your React components. The existing connect API still works and will continue to be supported, but the hooks API is simpler and works better with TypeScript.

但是如果您使用的是 Class 组件。您应该将 connectmapDispatchToProps 一起用作对象而不是函数。