反应SSR-使用D3进行SSR时为空HTML。使用useEffect挂钩

时间:2020-03-27 01:55:28

标签: javascript reactjs d3.js server-side-rendering

我有一些代码:https://codesandbox.io/s/d3-server-side-rendering-xpjhl

$(document).ready(function() {

    $('#datascape').DataTable( {
      responsive: true,

      lengthChange: true,
      pageLength: 15,
      language: {
      search: "_INPUT_",
      searchPlaceholder: "Search Records"
          },
      dom: '<"top"i>rt<"bottom"flp><"clear">',
      dom: 'Bfrtip',
      pagingType: "simple_numbers",

        buttons: [
            { extend: 'csvHtml5',
            footer: true,
            text:   'Download   <img src="/assets/images/icons/download.svg" class="downimage">',
            filename: function(){
                       var d = new Date();
                       month = '' + (d.getMonth() + 1),
                       day = '' + d.getDate(),
                       year = d.getFullYear();
                       var n = d.getTime();
                       var now = new Date();
                       var months = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC'];
                       var formattedDate = now.getFullYear() + months[now.getMonth()] + now.getDate();
                       return formattedDate + 'datascape from RQ'}

           },
        ],

我希望生成的HTML包含其中包含内容的SVG元素。大概我不了解import React from "react"; import ReactDOMServer from "react-dom/server"; import { select } from "d3"; const D3Example = () => { const data = [25, 30, 45, 60, 20]; const svgRef = React.useRef(null); React.useEffect(() => { const svg = select(svgRef.current); svg .selectAll("circle") .data(data) .join("circle") .attr("r", value => value) .attr("cx", value => value * 2) .attr("cy", value => value * 2) .attr("stroke", "red"); }, [data]); return ( <React.Fragment> <svg ref={svgRef} /> </React.Fragment> ); }; const html = ReactDOMServer.renderToString(<D3Example />); console.log(html); 钩子。呈现客户端时,仅不使用useEffect

时,此代码可以正常工作

我在做什么错了?

1 个答案:

答案 0 :(得分:1)

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_checked="false"> <bitmap android:src="@drawable/icon_home" android:tint="@color/white" /> </item> <item android:state_checked="true"> <bitmap android:src="@drawable/icon_home" android:tint="@color/grey" /> </item> <item> <bitmap android:src="@drawable/icon_home" android:tint="@color/white" /> </item> </selector> 在服务器端渲染期间不运行,与useEffect

相同

在服务器上渲染svg,请确保不要使用任何宽度或高度属性,因为它们在服务器上不存在

对于图表,我建议使用支持服务器端渲染的https://www.npmjs.com/package/recharts,有关更多信息:https://github.com/recharts/recharts/issues/71