React的切换如何工作
以下是一个简单的反应切换功能。但是我很困惑。在第一次点击中,我了解“ setState”函数使“状态”到“ true”,因此内容显示。但是在第二次点击中,“ setstate”已经是正确的。然后,错误状态如何工作。
- 首先单击按钮
- “变化”函数使“状态”对“ true”
- 状态'为“ true”,因此显示内容为
- 触发priggt pick phick pick picke theck the sight
- 会发生什么?
任何人都可以简单地解释它。提前致谢!
import React, {useState} from 'react'
function App() {
const [state,setState]=useState(false);
console.log(state);
const changeState=()=>{
setState(!state);
}
return (
<>
{state ? <div>Show Content</div> : null}
<button onClick={changeState}>Toggle</button>
</>
)
}
export default App
Following is a simple React Toggle functionality. But I have a confusion. In the first click, I understand that the 'setState' function makes the 'state' to 'true' so the content shows. But in the second click 'setState' is already true. Then how the false state working.
- First Click on the button
- 'changeState' function makes 'state' to 'true'
- 'state' is 'true' so the content is shows
- Trigger the second click
- What will happend ?
Can any one explain it in simple way. Thanks in advance!
import React, {useState} from 'react'
function App() {
const [state,setState]=useState(false);
console.log(state);
const changeState=()=>{
setState(!state);
}
return (
<>
{state ? <div>Show Content</div> : null}
<button onClick={changeState}>Toggle</button>
</>
)
}
export default App
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
状态
的初始值是false
。因此,首次单击后,您将state
设置为state
,这使其成为true
(因为!false
代码>等于true
)。在第二次单击中,它将变成false
,因为state
是true
,并将其设置为!状态
使其<代码> false (!true
等于false
)。感叹号(!
)被读取为不是。顺便说一句,我建议设置这样的状态:
希望这会有所帮助。
The initial value of
state
isfalse
. So, after you do the first click, you setstate
to!state
, which makes ittrue
(because!false
equalstrue
). On the second click, it will becomefalse
becausestate
wastrue
and setting it to!state
made itfalse
(!true
equalsfalse
). The exclamation mark (!
) is read as not.By the way, I recommend setting the state like this:
Hope this helps.
在setState并希望将上一个值作为输入时,您应该这样做:
在这里,我们通过在USESTATE函数中使用
Pre
获得当前值。这应该很好地工作。In react when you setState and want to use the previous value as the input you should do this:
Here we get the current value by using
pre
in the useState function. This should work perfectly.const usetoggle =(初始状态)=&gt; {
const [toggleValue,settoggleValue] = usestate(initialstate);
};
const useToggle = (initialState) => {
const [toggleValue, setToggleValue] = useState(initialState);
};