[英]Check if state is dirty or clean in React
我有一個狀態,其中包含一個項目和復選框列表,默認情況下這些項目和復選框被分配為 false 或 true(取決於我正在使用的 API)。
為簡單起見,假設我有這樣的狀態。
state = {
list: [
{
id: 0,
name: 'item1'
assigned: true
}
],
dirtyList: []
}
您可以做得更簡單。 創建一個起點並將其置於您的狀態。 在需要執行以下操作時,僅突變狀態並將其與startState進行比較:
const startState = {
a: true,
b: false
}
this.state = this.startState;
onSomeAction(){
if( JSON.stringify(startState) !== JSON.stringify(this.state){ /* ... */}
}
或者,您可以只檢查值:
onChange(key, evt){
if( this.state[key] !== this.startState[key] ){ /* ... */ }
// usage: this.onChange(event, 'a');
}
根據React文檔
由於this.props和this.state可以異步更新,因此您不應依賴於它們的值來計算下一個狀態。
this.setState((state)=>{
// some code here
const newState = [...state.list]
return {
list: newState
}
})
這就是我檢查文本字段是否臟的方式。
const [fullName, setFullName] = useState({name: '', dirty: false})
.....
const showError = () {
return fullName.dirty && isEmpty(fullName.name) //<- lodash isEmpty
}
<TextInput
...
onChangeText={(names) => {setFullName({name: names, dirty: true})}}
...
/>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.