Как использовать componentDidUpdate () для монтирования нового отчета об обновлении пути маршрута? - PullRequest
0 голосов
/ 25 марта 2020

Работа над панелью отчетов, где у меня есть встроенные отчеты PowerBI, отображающие данные для приложения данных, принадлежащих приложению, и попытки переключения между отчетами с помощью React Router и componentDidUpdate (). Наконец нашел статью, в которой предлагалось использовать componentDidMount () или componentDidUpdate () для этого типа экземпляра после нескольких часов поиска, как переключаться между отчетами, но не было достаточно четкого объяснения того, как его использовать.

Первый время использования этой функции и React Router, так что любые советы или рекомендации очень ценятся!

....

Подробнее:

У меня есть встроенные отчеты, отображающие как и предполагалось, когда вы выбираете один из них на странице spla sh после входа в приложение, но как только вы попадаете на панель инструментов отчета, где есть навигация по боковой панели, позволяющая пользователям переключаться между другими отчетами, я не могу -Рендер / монтировать к различным отчетам успешно. В настоящее время в консоли выводится 403 сообщения об ошибках, и из того, что я могу выяснить, похоже, что он не реинициализирует обновленные значения, используемые между различными отчетами в операторе switch в ReportDashboard. js

....

SplashPage. js

import React from 'react';
import Card from './Card';
import Report from './ReportDashboard';
import GridHeader from './GridHeading';

// Images
import Twilio from '../media/AB-Tests.png';
import Agent from '../media/Agent.png';
import B2C from '../media/B2C.png';
import ABTest from '../media/AB-Tests.png';

function SplashPage({ activeView, setActiveView, pageViewArray, reportArray }) {
  let pageHeading;
  let cardJSX;
  let iframeJSX;

  const dataList = [
    {
      header: pageViewArray[0],
      imageURL: B2C,
      info: 'Business to Consumer Data'
    },
    {
      header: pageViewArray[1],
      imageURL: B2B,
      info: 'Business to Business Data'
    },
    {
      header: pageViewArray[2],
      imageURL: Agent,
      info: 'Agent Data'
    }
  ];

  const reportList = [
    {
      screen: reportArray[0]  
    }
  ];

  if (activeView=== 'Default'){
    pageHeading =
    <GridHeader
      setActiveView={setActiveView}
    />
    cardJSX =
    <div className='card-holder'>  
      <Card
        data={dataList[0]}
        image={dataList[0].imageURL}
        setActiveView={setActiveView}
      />
      <Card
        data={dataList[1]}
        image={dataList[1].imageURL}
        setActiveView={setActiveView}
      />
      <Card
        data={dataList[2]}
        image={dataList[2].imageURL}
        setActiveView={setActiveView}
      />
    </div>
  } else if (activeView !== 'Default'){
    iframeJSX = <div className='frame-holder'>
      <Report
        report={reportList[0]}
        activeView={activeView}
      />
      <style>
        {`
        #root {
          height: 100vh;
          width: 100vw;
          overflow: hidden;
        }
        `}
      </style>
      </div>
  }
  return (
    <div>
      {pageHeading}
      {cardJSX}
      {iframeJSX}
    </div>
  );
}
export default SplashPage;

ReportDashboard. js

import React from 'react';
import {
  BrowserRouter as Router,
  Route,
  Link,
} from 'react-router-dom'
import { reportVariables } from '../constants/reportVariables.js'
import BackArrowImage from '../media/navigation_arrow_left.png';
import ReportRequest from './RequestAccessToken'

function Reporting({ activeView }) {
  // configure the reportIds and report name in constants/reportVariables.js
  let reportData;

  const routes = [
    {
      path: '/', // home
      exact: true,
      main: ()=> <h2>Dashboard</h2>,
    },
    {
      path: '/b2c',
      main: ()=> <h2>Business to Consumer</h2>,
    },
    {
      path: '/b2b',
      main: ()=> <h2>Business to Business</h2>,
    },
    {
      path: '/agent',
      main: ()=> <h2>Agent</h2>,
    },
    {
      path: '/ab-tests',
      main: ()=> <h2>A/B Tests</h2>,
    }
  ]

  switch(activeView){
    case 'Business to Consumer':
      reportData = <div>
        <ReportRequest
          reportID = {reportVariables.reportIds.b2c}
        />
      </div>
      break
    case 'Business to Business': 
    reportData = <div>
      <ReportRequest
        reportID = {reportVariables.reportIds.b2b}
      />
    </div>
      break
    case 'Agent':
      reportData = <div>
        <ReportRequest
          reportID = {reportVariables.reportIds.agent}

        />
      </div>
      break
    default: 
      break;
  }

  return(
    <div className='frameDiv'>  
        <Router>
            <div className="sideNav">
              <ul>
                <li><Link to='/'><img src={BackArrowImage} alt="Back Arrow" className="left-arrow"></img>Dashboard</Link></li>
                <li><Link to='/b2c'>Business to Consumer</Link></li>
                <li><Link to='/b2b'>Business to Business</Link></li>
                <li><Link to='/agent'>Agent</Link></li>
                <li><Link to='/ab-tests'>A/B Tests</Link></li>
              </ul>

              {routes.map((route) => (
                <Route
                  key={route.path}
                  path={route.path}
                  exact={route.exact}
                  component={route.sidebar}
                />
              ))}
            </div>
        </Router>


        {reportData}

    </div>
  ); 
}
export default Reporting

RequestAccessToken. js

import React, {useEffect, useState} from 'react';
import PowerbiEmbedded from 'react-powerbi'

function ReportRequest ({ reportID }) {
    // creates an array of the reportData
    const [reports, setReportData] = useState([]);
    const groupID = `abc`;

    componentDidUpdate(() =>{
        getReport();
    }, []);

    useEffect(() =>{
        getReport();
    }, []);

    const getReport = async () => {
        const response = await fetch(`/api/report/${reportID}`);
        const data = await response.json();
        setReportData(data.Token);
    }

    return (
    <div>  
        <PowerbiEmbedded
            id={reportID}
            embedUrl={`https://app.powerbi.com/reportEmbed?reportId=${reportID}&groupId=${groupID}&config=${config}`}
            accessToken={reports}
            filterPaneEnabled={true}
            navContentPaneEnabled={true}
            embedType={`report`}
            tokenType={`Embed`}
            permissions={`All`}
        />
    </div> 
)};


export default ReportRequest;
...