【发布时间】:2021-05-21 21:10:12
【问题描述】:
我的 Gatsby 网站的 header.js 包含一个带有徽标和链接的简单导航。如果“关于”页面处于活动状态:
- 链接文本应从“关于”更改为“关闭”
- 链接 URL 应从“/about”更改为“/”
见下面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)
}
})
【问题讨论】:
标签: reactjs gatsby setstate use-effect use-state