反应-服务呼叫被呼叫3次且未正确传递道具

时间:2020-04-28 18:24:11

标签: javascript reactjs redux axios

我正在编写使用React钩子使用React和Redux创建一个Webapp。我创建了一个service,可以要求axios对外部api进行全部处理并带回一些数据。然后将该数据插入Redux Store中,然后将组件state通过props传递给子组件。

我面临的问题是A。)父组件似乎正在加载3倍&B。)通过console output的计时如下:

reducer process time: 0.14
overview data {}
props undefined
overview data {accessibility: {…}, qa: {…}, seo: {…}, total: 88.52, _links: {…}}
SET_DASHBOARD_OVERVIEW
dispatching {type: "SET_DASHBOARD_OVERVIEW", webDashboard: {…}}
reducer process time: 0.03
next state {settings: Array(0), webDashboard: Array(1)}
overview data {accessibility: {…}, qa: {…}, seo: {…}, total: 88.52, _links: {…}}

我知道这是一个时序问题,当父/子组件加载时,尚未进行数据调用,因此没有数据可通过道具传递。我在努力弄清楚如何使它正常工作,因此aprent将加载,进行调用,获取数据并将数据传递给孩子。

Service.js

const axios = require('axios');
const moment = require('moment');

const siteImproveUrl = 'https://api.siteimprove.com/v2/sites/*******';

const authStr = '***********';

const getOverview = axios
    .get(siteImproveUrl + '/dci/overview', {params: {}, headers: {'Authorization': authStr}})
    .then(response => response.data)
    .catch(error => {
        if(error.response) {
            return error.reponse
        }
    });

module.exports = {
    getOverview
};

Dashboard.js

import React, { useState, useEffect } from 'react';
import { connect } from 'react-redux';

import QuickAnalytics from './quickAnalytics';
import TotalVisits from './totalVisits';
import PageRankings from './pageRankings';
import VisitsByHour from './visitsByHour';
import VisitLast30Days from './visitsLast30Days';

import 'chartist/dist/chartist';
import 'chartist/dist/chartist.min.css';

import './visitsByTime.scss';

import store from '../../../Redux/Store/store';
import { setDashboardOverview } from '../../../Redux/Actions/Actions';

const { getOverview } = require('../../../Util/Service');

const WebsiteDashboard = () => {
    const [overviewData, setOverviewData] = useState({});
    const [loading, setLoading] = useState(true);

    async function fetchData() {
        getOverview.then(result => {
            try {
                setLoading(true);
                setOverviewData(result);
                store.dispatch(setDashboardOverview({overview: overviewData}));
            } catch (e) {
                console.log(e); //TODO: Add Toast service
            } finally {
                setLoading(false);
            }
        });
    }

    useEffect(() => {
        if(loading) {
            fetchData();
        }
    }, [loading]);

    console.log('overview data',overviewData);

    return (
        <div>
            <div className="row">
                <div className="col">
                    <div className="card-chart card">
                        <div className="card-header">
                            <div className="row">
                                <div className="text-left col-sm-6">
                                    <h5 className="card-category">Website Admin</h5>
                                    <h3 className="card-title">Dashboard</h3>
                                </div>
                            </div>
                        </div>
                        <div className="card-body">
                            <div className="row">
                                <div className="text-left col-12">
                                    <QuickAnalytics overviewData={overviewData.qa}/>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div className="row">
                <div className="col-md-6">
                    <div className="card-chart card">
                        <div className="card-header">
                            <div className="row">
                                <div className="text-left col-sm-6">
                                    <h5 className="card-category">Total Visits Today</h5>
                                    <h3 className="card-title">Total: 6,550</h3>
                                </div>
                            </div>
                        </div>
                        <div className="card-body">
                            <div className="row">
                                <div className="text-left col-12">
                                    <TotalVisits />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div className="col-md-6">
                    <div className="card-chart card">
                        <div className="card-header">
                            <div className="row">
                                <div className="text-left col-sm-6">
                                    <h5 className="card-category">Top 5 pages</h5>
                                    <h3 className="card-title">As of: 06/26/20</h3>
                                </div>
                            </div>
                        </div>
                        <div className="card-body">
                            <div className="row">
                                <div className="text-left col-12">
                                    <PageRankings />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div className="row">
                <div className="col-md-12">
                    <div className="card-chart card">
                        <div className="card-header">
                            <div className="row">
                                <div className="text-left col-sm-6">
                                    <h5 className="card-category">Visits By Hour</h5>
                                    <h3 className="card-title">Total Page Visits: 34,890</h3>
                                </div>
                            </div>
                        </div>
                        <div className="card-body">
                            <div className="row">
                                <div className="text-left col-12">
                                    <VisitsByHour />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div className="row">
                <div className="col-md-12">
                    <div className="card-chart card">
                        <div className="card-header">
                            <div className="row">
                                <div className="text-left col-sm-6">
                                    <h5 className="card-category">Visits In The Last 30 Days</h5>
                                    <h3 className="card-title">Total Page Visits: 434,890</h3>
                                </div>
                            </div>
                        </div>
                        <div className="card-body">
                            <div className="row">
                                <div className="text-left col-12">
                                    <VisitLast30Days />
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}

export default connect()(WebsiteDashboard);

quickAnalytics.js

import React from 'react';
import { connect } from 'react-redux';

import ChartistGraph from 'react-chartist';

import './pieChart.scss';

let QA_data = {
    series: [80, 20]
};
let ADA_data = {
    series: [65, 35]
};
let SEO_data = {
    series: [50, 50]
};
let sum = function (a, b) { return a + b };

export default class QuickAnalytics extends React.Component {
    constructor(props) {
        super(props);
        console.log('props', props.overviewData);
        this.state = {
            data: props.overviewData
        };
    }

    render() {
        return (
            <div>
                <div className="row d-flex align-items-md-center mx-auto">
                    <div className="col text-center"> 
                        <div className="pieChart">
                            <h4>Site Improve QA</h4>
                            <ChartistGraph data={QA_data} options={
                                {
                                    labelInterpolationFnc: function (value) {
                                        return Math.round(value / QA_data.series.reduce(sum) * 100) + '%';
                                    },
                                    donut: true,
                                    donutWidth: 25,
                                    donutSolid: true,
                                    showLabel: true
                                }} type={'Pie'} />
                        </div>
                    </div>
                    <div className="col text-center">
                        <div className="pieChart">
                            <h4>ADA Accessibility</h4>
                            <ChartistGraph data={ADA_data} options={
                                {
                                    labelInterpolationFnc: function (value) {
                                        return Math.round(value / ADA_data.series.reduce(sum) * 100) + '%';
                                    },
                                    donut: true,
                                    donutWidth: 25,
                                    donutSolid: true,
                                    showLabel: true
                                }} type={'Pie'} />
                        </div>
                    </div>
                    <div className="col text-center">
                        <div className="pieChart">
                            <h4>SEO</h4>
                            <ChartistGraph data={SEO_data} options={
                                {
                                    labelInterpolationFnc: function (value) {
                                        return Math.round(value / SEO_data.series.reduce(sum) * 100) + '%';
                                    },
                                    donut: true,
                                    donutWidth: 25,
                                    donutSolid: true,
                                    showLabel: true
                                }} type={'Pie'} />
                        </div>
                    </div>
                </div>
            </div>
        )
    }

}

1 个答案:

答案 0 :(得分:0)

我通过在子组件周围添加条件加载来解决此问题:

{loading ? (
    <div> Loading...</div>
) : (
    <QuickAnalytics overviewData={overviewData.qa} />
)}