【问题标题】:Reducer passing state as props in a component undefined减速器将状态作为组件中的道具传递未定义
【发布时间】:2019-03-29 11:19:05
【问题描述】:

我的 Reducer 和 Actions 工作正常,我正在记录我的数据,但是我在使用 reducer 状态的组件中的日志返回 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


    【解决方案1】:

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

    如果您需要打印对象,请尝试以下操作:

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

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

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

    【讨论】:

      【解决方案2】:

      你的减速器是 GET_ASSET_BY_ID 你的操作是 GET_REPORT_BY_ID

      【讨论】:

      • 这是我在这里输入时犯的一个错误...我的代码在 reducer 和 actons 中有 GET_REPORT_BY_ID
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-11
      • 2019-02-20
      • 2017-04-30
      • 1970-01-01
      • 2019-05-11
      • 2019-05-17
      • 2017-11-19
      相关资源
      最近更新 更多