This is down to the basic way that React works, when you change the state
of a component, it re-renders itself with the new values you've set into state
.(这取决于React的基本工作方式,当您更改组件的state
时,它会使用您已设置为state
的新值来重新渲染自身。)
Specifically it's this bit of Header.js:(具体来说就是Header.js的这一点:)
{context.state.isNavOpen && (
<div className="js-nav nav">
...
When the component renders the first time, context.state.isNavOpen
is false, and false && anything
is still false, so javascript ignores the code after the &&
.(当组件第一次呈现时, context.state.isNavOpen
为false,而false && anything
仍然为false,因此javascript会忽略&&
之后的代码。) That means it skips over the menu code.(这意味着它将跳过菜单代码。)
The second time it renders, after you update the state which is pushed to context and then passed to <Header>
as a prop (!), the component re-renders with your menu code.(第二次渲染时,更新状态后将其推送到上下文,然后将其作为prop(!)传递给<Header>
,该组件将使用菜单代码重新渲染。)
If you use your browser's dev tools to inspect the DOM before and after you click the button, you'll find that the menu isn't hidden and shown, but rather when you don't see it, it's gone from the DOM altogether.(如果您使用浏览器的开发工具在单击按钮之前和之后检查DOM,则会发现菜单没有隐藏和显示,但是当您看不到菜单时,菜单就完全脱离了DOM。) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…