Redux Thunk 和异步操作

Redux Thunk and Async Actions

我收到两个错误,我已将其缩小为与 thunk 和异步操作相关。

第一个是“错误:操作必须是普通对象。使用自定义中间件进行异步操作。”

第二个是“未处理的拒绝(类型错误):error.response 未定义”

项目的githublink在这里:https://github.com/paalpwmd/react_front_to_back/tree/master/itlogger

我的获取日志操作如下所示...

得到

// Get logs from server
export const getLogs = async (dispatch) => {
  try {
    setLoading();

    const res = await fetch('/logs');
    const data = await res.json();

    dispatch({
      type: GET_LOGS,
      payload: data,
    });
  } catch (error) {
    dispatch({
      type: LOGS_ERROR,
      payload: error.response.data,
    });
  }
};

实现getLogs函数的文件如下所示..

import Preloader from '../layout/Preloader';
import LogItem from './LogItem';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getLogs } from '../../actions/logActions';

const Logs = ({ log: { logs, loading }, getLogs }) => {
  useEffect(() => {
    getLogs();
    //   eslint-disable-next-line
  }, []);

  if (loading || logs === null) {
    return <Preloader />;
  }

  return (
    <div>
      <ul className='collection with-header'>
        <li className='collection-header'>
          <h4 className='center'>System Logs</h4>
        </li>
        {!loading && logs.length === 0 ? (
          <p className='center'>No logs to show...</p>
        ) : (
          logs.map((log) => <LogItem log={log} key={log.id} />)
        )}
      </ul>
    </div>
  );
};

Logs.propTypes = {
  log: PropTypes.object.isRequired,
};

const mapStateToProps = (state) => ({
  log: state.log,
});

export default connect(mapStateToProps, { getLogs })(Logs);

我怎样才能正确地接受行动中的承诺?

发现 getLogs 缺少箭头函数。

正确的语法是:

getLogs = ()=> async (dispatch) => {...}