gpt4 book ai didi

javascript - 如何为 GatsbyJS 制作仅客户端组件?

转载 作者:行者123 更新时间:2023-12-04 15:24:08 26 4
gpt4 key购买 nike

我如何为 Gatsby 创建一个将在客户端加载而不是在构建时加载的组件?

我创建了这个,它使用 gatsby develop 呈现,但不使用呈现的服务器端呈现

import React from 'react';
import axios from 'axios';
import adapter from 'axios-jsonp';

export default class Reputation extends React.Component<{}, { reputation?: number }> {
constructor(props) {
super(props);
this.state = {};
}

async componentDidMount() {
const response = await axios({
url: 'https://api.stackexchange.com/2.2/users/23528?&site=stackoverflow',
adapter
});
if (response.status === 200) {
const userDetails = response.data.items[0];
const reputation = userDetails.reputation;
this.setState({
reputation
});
}
}

render() {
return <span>{ this.state.reputation?.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",") }</span>
}
}

最佳答案

如果您不想在构建时将组件捆绑在主 js 文件中,请使用 loadable-components

Install loadable-components and use it as a wrapper for a component that wants to use a client-side only package. docs

import React, { Component } from "react";
import Loadable from "@loadable/component";

const LoadableReputation = Loadable(() =>
import("../components/Reputation")
);

const Parent = () => {
return (
<div>
<LoadableReputation />
</div>
);
};

export default Parent;

关于javascript - 如何为 GatsbyJS 制作仅客户端组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62679128/

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