gpt4 book ai didi

javascript - 为什么 renderToString 在渲染 Material-UI 组件时会抛出有关 useLayoutEffect 的错误?

转载 作者:行者123 更新时间:2023-12-05 00:34:11 25 4
gpt4 key购买 nike

我正在使用 React v.16.12.0 和 @MaterialUI/core v4.8.1。

我正在尝试为 React Leaflet Marker 创建自定义图标。图标是 Fab Material-UI 中的组件。为此,我需要将 HTML 字符串传递给 L.DivIcon (DivIcon Docs)传单组件,所以我使用 renderToString()来自 react-dom/server 的方法.

它抛出一个错误:

Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. in NoSsr in button in ForwardRef(ButtonBase) in WithStyles(ForwardRef(ButtonBase)) in ForwardRef(Fab) in WithStyles(ForwardRef(Fab)) (at src/index.js:9)



虽然我没有使用 useLayoutEffect。

这是一个简单的例子:
import React from "react";
import ReactDOM from "react-dom";
import ReactDOMServer from 'react-dom/server';
import Fab from '@material-ui/core/Fab';

function App() {
return ReactDOMServer.renderToString(
<Fab size="small" variant="extended">
Test
</Fab>);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

在线: https://codesandbox.io/s/material-ui-rendertostring-tc90b

为什么会抛出该错误?这段代码有什么问题?有没有其他方法可以从 Material-UI 组件生成 HTML-String 以便将其作为图标传递给 Leaflet Marker?

最佳答案

我用了renderToStaticMarkup呈现自定义标记。标记正在渲染,但仍然收到警告。

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { renderToStaticMarkup } from "react-dom/server";
import { divIcon } from "leaflet";
import { Map, TileLayer, Marker, Popup } from "react-leaflet";
import Fab from "@material-ui/core/Fab";

import "./styles.css";

class App extends Component {
state = {
lat: 51.505,
lng: -0.091,
zoom: 13
};

render() {
const position = [this.state.lat, this.state.lng];
const iconMarkup = renderToStaticMarkup(
<Fab size="small" variant="extended">
Test
</Fab>
);
const customMarkerIcon = divIcon({
html: iconMarkup
});

return (
<div>
<Map center={position} zoom={this.state.zoom}>
<TileLayer
attribution='&amp;copy <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.osm.org/{z}/{x}/{y}.png"
/>
<Marker position={position} icon={customMarkerIcon}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</Map>
</div>
);
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

工作代码: https://codesandbox.io/s/react-leaflet-icon-material-mx1iu

关于javascript - 为什么 renderToString 在渲染 Material-UI 组件时会抛出有关 useLayoutEffect 的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59480303/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com