Redux Thunk和异步操作

问题描述 投票:1回答:1

我发现了两个错误,这些错误已缩小为与重击和异步操作有关。

首先是“错误:操作必须是普通对象。使用自定义中间件执行异步操作。”

第二个是“未处理的拒绝(TypeError):error.response未定义”]

该项目的github链接在这里: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);

我如何正确地接受诺言?

javascript reactjs redux thunk
1个回答
0
投票

发现getLogs缺少箭头功能。

正确的语法为:

getLogs = ()=> async (dispatch) => {...}
© www.soinside.com 2019 - 2024. All rights reserved.