![](/img/trans.png)
[英]return value is not rendering when returned from inside the handleclick() function in react
[英]How does this handleClick function in React retrieve previous state value?
此codepen將按鈕值從true
切換為false
。
除了這個handleClick
function 是如何工作的之外,我理解這一點:
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
有人可以將其分解並簡單地解釋 function 如何檢索isToggleOn
布爾值嗎?
我知道我們不能直接在setState
中使用.this.state.isToggleOn
但有人可以簡單地解釋一下為什么這個handleClick
function 在這種情況下對於 React 新手來說更可靠嗎?
這就是調用handleClick
function 的地方:
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
從setState
文檔:
第一個參數是帶有簽名的更新程序 function:
(state, props) => stateChange
state
是在應用更改時對組件 state 的引用。
在您的示例prevState
是重命名的state
,它包含 state 中的所有分配,包括isToggleOn
。
您也可以在setState
function 中閱讀this.state
。 prevState
模式用於傳達這是舊的/當前的 state、正在更改的 state。
在這種情況下,您實際上可以同時使用兩者,因為它非常簡單,您可以從渲染 function 調用 setState。 在 class 組件中很難找到this.setState({oldState:this.state.oldState})
可能有問題的地方。 相反,如果你使用函數式組件或鈎子,你會經常看到這個問題。
要理解這一點,您必須首先認為 js不是面向 object 的語言。 React 試圖模擬它。 基本上,當您更改 state 時,包含它的 class 會再次被調用,試圖僅運行更改的代碼。 在您的情況下,當調用handleClick
時, render
function 被觸發,因為 state 已更改!
說到這里,handleClick 不僅僅是一個 function。 它也是 class 的屬性。 React 試圖了解它是否應該根據它們使用的值“重新聲明”這些函數。
在您編寫的情況下, isToggleOn: .prevState.isToggleOn
, function 是獨立的。 它不需要 class 的任何其他屬性(除了 setState,它使用不同的模式),因此在 state 更改后,反應引擎不必再次設置 ZC1C425268E68385D1AB5074C17A
On the contrary if you use isToggleOn: .this.state.isToggleOn
the handleClick
function is dependent of this.state
so every time it changes, the react engine has to "re-declare" the function by sort of substituting this.state
with {isToggleOn:...}
function myRandom(property){ //Kind of private Variable let hiddenVar=Math.random(); return property(hiddenVar); } //Let's say here the Math class is unreachable while myRandom is. myRandom((num)=>{ console.log(num);//This ac })
也許只是檢查一下文檔?
setState() 的第二個參數是一個可選的回調 function,它將在 setState 完成並重新渲染組件后執行。 通常我們建議使用 componentDidUpdate() 來代替這種邏輯。
本質上,您將在 function 中獲取 state 的先前實例,然后對 state 進行更改並返回它。 這個新的 state 將被保存並導致重新渲染您的組件。
如果您使用函數式組件,您可以不必在此處傳遞回調,並且可以執行以下操作:
function MyComponent() {
const [on, setOn] = React.useState(false)
return (
<button onClick={() => setOn(!on)}>
{on? 'ON' : 'OFF'}
</button>
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.