Reducer传递状态作为组件中的道具未定义

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

我的Reducer和Actions工作正常,我正在记录我的数据,但是我在使用reducers状态的组件中的日志返回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);
reactjs reducers
2个回答
0
投票

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

如果您需要打印物体,请尝试以下方法:

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

如果未格式化的JSON适合你,你可以跳过第二个和第三个stringify参数。

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


0
投票

你的reducer是GET_ASSET_BY_ID,你的行动是GET_REPORT_BY_ID

© www.soinside.com 2019 - 2024. All rights reserved.