所以我有一个使用Next.js的SSR应用程序。我正在使用第三方组件,该组件利用WEB API,因此需要在客户端加载而不是服务器上加载。我正在使用“两次渲染”,我在这里阅读了相关信息:https://itnext.io/tips-for-server-side-rendering-with-react-e42b1b7acd57
我试图弄清楚为什么当next.js页面状态中的“ssrDone”状态更改时,整个
我已经阅读过
我的控制台日志消息
在控制台中,输出为:
<Layout>
组件都会不必要地重新渲染,其中包括页面的页头、页脚等。我已经阅读过
React.memo()
以及利用 shouldComponentUpdate()
,但似乎无法阻止它重新渲染<Layout>
组件。我的控制台日志消息
<Layout>
会触发两次,但<ThirdPartyComponent>
的控制台消息只会触发一次,就像预期的那样。这是一个问题吗?还是React足够聪明,不会实际更新DOM,所以我甚至不需要担心这个问题。看起来很愚蠢,没有理由重新渲染我的页面页头和页脚。在控制台中,输出为:
Layout rendered
Layout rendered
3rd party component rendered
index.js(next.js页面)
import React from "react";
import Layout from "../components/Layout";
import ThirdPartyComponent from "../components/ThirdPartyComponent";
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
ssrDone: false
};
}
componentDidMount() {
this.setState({ ssrDone: true });
}
render() {
return (
<Layout>
{this.state.ssrDone ? <ThirdPartyComponent /> : <div> ...loading</div>}
</Layout>
);
}
}
export default Home;
ThirdPartyComponent.jsx
import React from "react";
export default function ThirdPartyComponent() {
console.log("3rd party component rendered");
return <div>3rd Party Component</div>;
}
Layout.jsx
import React from "react";
export default function Layout({ children }) {
return (
<div>
{console.log("Layout rendered")}
NavBar here
<div>Header</div>
{children}
<div>Footer</div>
</div>
);
}
<Layout>
内部的console.log仍然运行两次(渲染两次?),就像我的示例一样? - Taylor A. Leach