嵌入Power BI报表时如何在react js中初始化useState变量

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

我正在尝试使用

powerbi-client-react
库将 power bi 报告嵌入到 React js 组件中。我面临的问题是当
useState
变量被传递或用特定值初始化时渲染 power bi 报告。在这种情况下,报告显示正常,但如果初始化变量没有任何值(即空字符串),则报告不会呈现。在这里寻找一些指南。

我有两个反应组件。以A和B为例。我从组件 A 向组件 B 传递几个值,组件 B 具有

<PowerBIEmbed />
来显示报告。

我怀疑我不完全知道如何有效地使用这些

useState
useEffect
钩子。

在下面的代码中,如果我在组件 A 中为 reportId 和 embedUrl 设置 useState hooks 变量,则报告加载不会出现问题。

A 组件代码:

import React, { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import axios from "axios";
import { componentB } from "./componentB";

const componentA = () => {
  const { state } = useLocation();
  let Id = state.id;
  let Value = state.data;

  /* Above values are coming from other parent component */

  const location = useLocation();
  const [details, setDetails] = useState([]);
  const [reportId, setReportId] = useState("");
  const [embedUrl, setEmbedUrl] = useState("");

  /*if this variable is initialized with reportId instead of empty string, report loads perfectly 
      without issue, but that is not the case*/

  let customerId = location.state.customerId;

  useEffect(() => {
    const getUrl = "http://localhost:8080/Api/GetData/" + customerId;
    const fetchData = async () => {
      try {
        const response = await axios.get(getUrl);
        const data = await response.data;
        setDetails(data);
        url = new URL(data.visualizationUrl);
        const queryParam = new URLSearchParams(url.search);
        setReportId(queryParam.get("reportId"));
        setEmbedUrl(url.href);
      } catch (e) {
        console.log("error", e);
      }
    };
    fetchData();
  }, [customerId]);

  return (
    <>
      <div>
        <p>details.customerName</p>
        <p>details.customerAddress</p>
      </div>
      <div>
        <componentB reportId={reportId} embedUrl={embedUrl} />
      </div>
    </>
  );
};

export default componentA;

B 组件代码:

import React from "react";
import { PowerBIEmbed } from "powerbi-client-react";
import { models } from "powerbi-client";

const componentB = (props) => {
  const reportId = props.reportId;
  console.log("report id:", reportId);

  const embedUrl = props.embedUrl;
  console.log("embed url:", embedUrl);

  return (
    <div>
      <PowerBIEmbed
        embedConfig={{
          type: "report",
          id: reportId,
          embedUrl: embedUrl,
          accessToken: "long string of power bi access token",
          tokenType: models.TokenType.Aad, // Use models.TokenType.Aad for SaaS embed
          settings: {
            panes: {
              filters: {
                expanded: false,
                visible: false,
              },
            },
            background: models.BackgroundType.Transparent,
          },
        }}
        eventHandlers={
          new Map([
            [
              "loaded",
              function () {
                console.log("Report loaded");
              },
            ],
            [
              "rendered",
              function () {
                console.log("Report id: ", reportId);
              },
            ],
            [
              "error",
              function (event) {
                console.log(event.detail);
              },
            ],
            ["visualClicked", () => console.log("visual clicked")],
            ["pageChanged", (event) => console.log(event)],
          ])
        }
        cssClassName={"reportClass"}
        getEmbeddedComponent={(embeddedReport) => {
          window.report = embeddedReport;
        }}
      />
    </div>
  );
};

export default componentB;
reactjs powerbi-embedded
1个回答
0
投票

这里有一些问题...

  1. componentB
    是默认导出,但您尝试将其导入为命名
  2. React 强制组件名称采用 PascalCased
  3. 当新数据到达时,您没有任何信息告诉
    PowerBIEmbed
    componentB
    重新渲染
  4. 没必要
    await response.data

我的建议是

  1. componentB
    重命名为
    ComponentB

  2. 导入默认导出

    import ComponentB from './componentB';
    
  3. 使用

    key
    属性来确保
    ComponentB
    使用新数据重新渲染

    <ComponentB key={reportId} reportId={reportId} embedUrl={embedUrl} />
    

    或使用条件渲染,这将避免尝试嵌入空的 PowerBI 数据

    {
      reportId ? (
        <ComponentB reportId={reportId} embedUrl={embedUrl} />
      ) : (
        <p>Loading...</p>
      );
    }
    
© www.soinside.com 2019 - 2024. All rights reserved.