0

这是一个简化的 React 组件,它使用头盔在运行时更新链接 css:

function App() {
  const [brand, setBrand] = useState('nike')
  return (
    <div className="App">
      <Helmet>
        <link rel="stylesheet" href={getBrandStyle(brand)} />
      </Helmet> 
      <div>other contents here</div>
      <!-- omitted the button components that change the brand state by calling setBrand -->
    </div>
  );
}

我最近刚刚使用 react-helmet 作为一种声明性方式来更改 head 标签的子标签,并且使用我上面编写的代码,在切换 css 时,当页面没有 css 样式时会出现瞬间延迟,然后 1 秒后更新的 css 显示向上。

即使在页面的初始加载期间,如果我使用 queryParameters (上面的代码没有显示查询参数方法),例如

https://localhost:3000?brandQueryParam=nike

在品牌 css 出现之前,有 1 秒钟没有 css 样式。

你能告诉我我缺少什么以及如何解决这个问题吗?

4

1 回答 1

0

这是我想出的解决方案,不确定 setTimeout 是否是最好的解决方案,所以如果其他人知道更好的方法,请分享。

const brands = {
  nike: 'nike2022',
  adidas: 'adidas2017',
  fila: 'fila2020'
};

function App() {
  const [brand, setBrand] = useState('nike')
  const [isLoading, setIsLoading] = useState(false)
  const changeBrandStyleOnClick = (brand) => {
    setBrand(brand)
    setIsLoading(true)
  }

  return (
    <div className="App">
      <Helmet>
        <link rel="stylesheet" 
              onChangeClientState={(newState, addedTags, removedTags) => setTimeout(() => setIsLoading(false), 1500)}
              href={getBrandStyle(brand)} />
      </Helmet> 
      {isLoading && (
        <Overlay>
          <Spinner/>
        </Overlay>
      )}

      {!isLoading && (
        <>
          {Object.keys(brands).filter(b => b !== brand).map(b =>
            (<Button onClick={() => changeBrandStyleOnClick (b)} value={b}>
            <Logo
              alt="default alt name"
              appearance="default"
              name={b}
              size="small"/>
            </Button>))
          }
          <div>other contents here</div>
        </>
      )}
    </div>
  );
}
于 2022-02-22T23:44:04.273 回答