【问题标题】:Redux Thunk and Async ActionsRedux Thunk 和异步操作
【发布时间】:2020-04-09 21:37:51
【问题描述】:

我遇到了两个错误,我已将其范围缩小为与 thunk 和异步操作有关。

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

第二个是“Unhandled Rejection (TypeError): error.response is undefined”

项目的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】:

    发现 getLogs 缺少箭头功能。

    正确的语法是:

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

    【讨论】:

      猜你喜欢
      • 2018-01-31
      • 2019-12-17
      • 2017-03-03
      • 2021-10-04
      • 2020-01-17
      • 2016-12-20
      • 2016-10-24
      • 2016-09-19
      • 2018-03-20
      相关资源
      最近更新 更多