反应/Redux 应用程序操作未正确调度

React/Redux app actions not being dispatched properly

本文关键字:调度 操作 Redux 应用程序 反应      更新时间:2023-09-26

我正在尝试使用 Redux 设置我的第一个 React 应用程序,但我目前在调度操作时遇到了一些问题。到目前为止,我有以下文件用于我的操作:

常量/身份验证操作类型.js:

export const AUTH_PENDING = 'AUTH_PENDING';
export const AUTH_SUCCESS = 'AUTH_SUCCESS';
export const AUTH_FAIL = 'AUTH_FAIL';

actions/authActions.js:

import * as AuthActionTypes from '../constants/AuthActionTypes';
function authPending() {
  return { type: AuthActionTypes.AUTH_PENDING };
}
function authSuccess(response) {
  return { type: AuthActionTypes.AUTH_SUCCESS };
}
export function login(username, password) {
  return dispatch => {
    dispatch(authPending());
    // nothing really happens yet
    dispatch(authSuccess());
  };
}

我还有一个包含HTML表单的登录组件,以及一个在提交表单时调用的login函数。

组件/登录.js

...
login (e) {
  e.preventDefault();
  var username = ReactDOM.findDOMNode(this.refs.username).value;
  var password = ReactDOM.findDOMNode(this.refs.password).value;
  this.props.dispatch(AuthActions.login(username, password));
}
...

该功能已触发,但是...有些不对劲。我使用 redux-devtools ,它只调度一个动作 - 当然,它应该调度来自authPendingauthSuccess的操作?此外,devtools 窗格不显示任何操作类型,我在控制台中收到以下警告:

警告:失败的道具类型:无效的道具action类型为 function 供应给LogMonitorEntry,预计object。检查渲染 LogMonitor法 .

我在这里做错了什么?我错过了什么?我主要查看了 https://github.com/rackt/redux/tree/master/examples/real-world 和 https://github.com/yildizberkay/redux-example 的示例,我看不出我正在做什么不同的事情,使我自己的应用程序崩溃。

...几分钟后,我偶然发现了答案:我没有将redux-thunk中间件应用于我的商店。应用它,一切都按预期工作。

你可以做 w/o thunk。改变

this.props.dispatch(AuthActions.login(username, password));

this.props.dispatch(AuthActions.authPending());
this.props.dispatch(AuthActions.authSuccess());

当然,您必须导入这两个方法/操作创建者。