Reducer 在未定义的组件中将状态作为 props 传递

Reducer passing state as props in a component undefined

我的 Reducer 和 Actions 工作正常,我正在记录我的数据,但是我在使用我的 reducer 的组件中的日志状态 returns props 作为 [object object],我确定我不是正确记录或以正确格式读取 json。这是代码:

reportReducer.js

import { GET_REPORTS, GET_REPORT_BY_ID } from '../actions/types';
const initialState = {
    reports: [],
    report: {}
};

export default function(state = initialState, action) {
    switch (action.type) {
        case GET_REPORTS:
            return {
                ...state,
                reports: action.payload
            };
        case GET_REPORT_BY_ID:
            return {
                ...state,
                report: action.payload
            };
        default:
            return state;
    }
}

reportActions.js

import {GET_REPORTS, GET_REPORT_BY_ID} from './types';
import axios from 'axios';

export const getReports = () => async dispatch => {
    const res = await axios.get(`/api/report`);
    dispatch({
        type: GET_REPORTS,
        payload: res.data
    });
};

export const getReportById = id => async dispatch => {
    const res = await axios.get(`api/report/${id}`);
    console.log(res.data);
    dispatch({
        type: GET_REPORT_BY_ID,
        payload: res.data
    });
};

ReportById.jsx

import React, {Component} from 'react';
import {getReportById} from '../../actions/reportActions';
import {connect} from 'react-redux';

class ReportById extends Component {
    constructor(props) {
        super(props);
    }

    componentDidMount = async () => {
        this.props.getReportById(this.props.match.params.id);
    };

    render() {
          console.log(this.props.match.params.id);
          console.log(this.props);   \this gives [object object]


        return (
            <div>
                <div>
                   <ul>
                    {report && report.title && (
                       <li > {report.title} | {report.assetType} </li>
                                )}
                        </ul>
                </div>
            </div>
        );
    }
}

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

export default connect(mapStateToProps, {getReportById})(ReportById);

你的reducer是GET_ASSET_BY_ID 而你的动作是 GET_REPORT_BY_ID

使用 console.log 打印对象将始终打印 [object Object]。发生这种情况是因为 console.log 将尝试通过调用 toString 将其参数转换为字符串。

如果您需要打印对象,请尝试这样的操作:

console.log(JSON.stringify(this.props, null, 2));

如果未格式化 JSON 适合您,您可以跳过字符串化的第二个和第三个参数。

请注意,如果您在 props 中传递任何圆形对象,这将不起作用。