Sma*_*Sax 2 javascript checkbox reactjs
我有一个状态,其中包含默认分配为 false 或 true 的项目和复选框列表(取决于我正在使用的 API)。
为了简单起见,我们假设我的状态是这样的。
state = {
list: [
{
id: 0,
name: 'item1'
assigned: true
}
],
dirtyList: []
}
Run Code Online (Sandbox Code Playgroud)
单击复选框时,您按下一个按钮,弹出窗口会告诉您该项目是否已注册或删除(复选框为真/假)。但是,假设您在已选中复选框的情况下启动页面,然后单击它两次(使其再次选中为真),弹出窗口不应显示该项目已注册,因为原始状态尚未更改。(它从true,出发false,然后返回true)
这是我的复选框handleChange函数
checkboxChanged = (event, id) => {
let isChecked = event.target.checked
const index = this.state.list.findIndex(list => list.id === id)
const newState = [...this.state.list]
let newList = { ...newState[index] }
console.log(newList)
// By console logging this, it eventually tells me the previous state of the item that was clicked
newState[index].assigned = isChecked
this.setState({
list: newState,
})
}
Run Code Online (Sandbox Code Playgroud)
我很难弄清楚如何/在哪里更新状态'dirtyList',因为只有这样我才能将原始状态与脏状态进行比较。
你可以做得更简单。创建一个起点并将其放入您的状态中。当您需要时,仅改变状态并将其与 startState 进行比较:
const startState = {
a: true,
b: false
}
this.state = this.startState;
onSomeAction(){
if( JSON.stringify(startState) !== JSON.stringify(this.state){ /* ... */}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以只检查值:
onChange(key, evt){
if( this.state[key] !== this.startState[key] ){ /* ... */ }
// usage: this.onChange(event, 'a');
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
13766 次 |
| 最近记录: |