首页 > 解决方案 > 如何使用 getProps 和 setState 更改 Gatsby Link 文本

问题描述

我的 Gatsby 网站的 header.js 包含一个带有徽标和链接的简单导航。如果“关于”页面处于活动状态:

请参阅下面的 header.js 代码:

import React, { useState } from "react"
import { Link } from "gatsby"

export default function Header() {
  const [aboutLink, setAboutLink] = useState({
    title: "About",
    url: "/about",
  })

  const closeLink = {
    title: "Close",
    url: "/",
  }

  const isActive = ({ isCurrent }) => {
    return isCurrent && setAboutLink(closeLink)
  }

  return (
    <div id="header">
      <Link to="/">My Website</Link>
      <Link getProps={isActive} to={aboutLink.url}>{aboutLink.title}</Link>
    </div>
  )
}

我试图用它来实现这一点,setState它似乎工作。但不正确,因为我也在控制台中收到此错误:

Warning: Cannot update a component (`Header`) while rendering a different component (`Context.Consumer`). To locate the bad setState() call inside `Context.Consumer`, follow the stack trace as described in https://github.com/facebook/react/issues/18178#issuecomment-595846312
    in Location (created by Context.Consumer)
    in Link (created by GatsbyLink)
    in GatsbyLink (created by Context.Consumer)
    in Location (created by GatsbyLinkLocationWrapper)
    in GatsbyLinkLocationWrapper (created by ForwardRef)
    in ForwardRef (at header.js:22)
    in div (at header.js:20)
    in Header (at layout.js:8)
    in div (at layout.js:7)
    in Layout (at about.js:21)
    in About (created by HotExportedAbout)
    in AppContainer (created by HotExportedAbout)
    in HotExportedAbout (created by PageRenderer)
    in PageRenderer (at query-result-store.js:90)
    in PageQueryStore (at root.js:58)
    in RouteHandler (at root.js:80)
    in div (created by FocusHandlerImpl)
    in FocusHandlerImpl (created by Context.Consumer)
    in FocusHandler (created by RouterImpl)
    in RouterImpl (created by Context.Consumer)
    in Location (created by Context.Consumer)
    in Router (at root.js:75)
    in ScrollHandler (at root.js:71)
    in RouteUpdates (at root.js:70)
    in EnsureResources (at root.js:68)
    in LocationHandler (at root.js:126)
    in LocationProvider (created by Context.Consumer)
    in Location (at root.js:125)
    in Root (at root.js:134)
    in StaticQueryStore (at root.js:150)
    in ConditionalFastRefreshOverlay (at root.js:149)
    in _default (at app.js:165)

我想不通。如果我useEffect在此示例中使用https://flaviocopes.com/react-update-while-rendering-different-component/我会收到此错误'isActive' is not defined

useEffect(() => {
  const isActive = ({ isCurrent }) => {
    return isCurrent && setAboutLink(closeLink)
  }
})

标签: reactjsgatsbysetstateuse-effectuse-state

解决方案


您需要更改isActive属性,isCurrent或者使用isPartiallyCurrent,正如您从文档中看到的那样:

Gatsby 的<Link>组件带有一个getPropsprop,它可以用于高级样式。它向您传递具有以下属性的对象:

  • isCurrent— 如果 the与组件的 to proplocation.pathname完全相同,则为 true<Link>
  • isPartiallyCurrenttrue如果 location.pathname<Link>组件的 to 属性开头
  • href— to 的值prop
  • location— 页面的location对象

你可以阅读更多关于它@reach/router的文档

相关话题:


推荐阅读