我试图将我的复选框选中值存储到我的react应用中的localstorage中。但每次我存储,它将存储以前的状态。以下是我的代码:
对于渲染方:
main.Parent (struct with 6 fields)
Name string (string)
Surname *string (ptr to string)
Children []*main.child (slice of ptr to struct with 2 fields)
Name *string (ptr to string)
Age int (int)
PetNames []string (slice of string)
Parents [2]*main.Parent (array with 2 elements of ptr to struct with 6 fields)
child main.child (struct with 2 fields)
对于onchange方法:
render () {
return (
<Checkbox
checked={this.state.checkedCheckpoint}
onChange={() => this.onChange('checkpoint')}
>
</Checkbox>
)
前一个州的意思是:
如果我将检查点初始化为真,那么在取消选中后,我应该 onChange (value){
const { checkedCheckpoint } = this.state
if (value === 'checkpoint')
{
if (checkedCheckpoint)
{
this.setState({checkedCheckpoint : false})
console.log(checkedCheckpoint)
}
else
{
this.setState({checkedCheckpoint : true})
console.log(checkedCheckpoint)
}
}
localStorage.setObject('checkedCheckpoint', checkedCheckpoint)
正确吗?但我得到checkpoint: false
。如果我查了一下,我应该checkedCheckpoint: true
对吗?我会得到checkedCheckpoint: true
。似乎它将始终遵循localstorage中的先前状态。任何人都知道什么是错的?
答案 0 :(得分:4)
你需要将你想要执行状态更改的任何逻辑作为第二个参数传递给this.setState()
示例:
state = {
name: 'Johnny'
}
someMethod = () => {
this.setState({name: 'Tim'})
doSomethingElse(this.state.name) //doSomethingElse receives Johnny
}
我认为您正在寻找的是
state = {
name: 'Johnny'
}
someMethod = () => {
this.setState({name: 'Tim'}, doSomethingElse(this.state.name))
//doSomethingElse receives Tim
}
请参阅setState here的文档。
答案 1 :(得分:0)
您需要根据新值而不是旧值来设置
onChange (value){
const { checkedCheckpoint } = this.state
if (value === 'checkpoint')
{
if (checkedCheckpoint)
{
this.setState({checkedCheckpoint : false})
localStorage.setObject('checkedCheckpoint', false)
console.log(checkedCheckpoint)
}
else
{
this.setState({checkedCheckpoint : true})
localStorage.setObject('checkedCheckpoint', true)
console.log(checkedCheckpoint)
}
}
答案 2 :(得分:0)
React尝试批处理setState命令。它更像是一个异步任务。因此,当您执行this.setState({checkedCheckpoint:true})时,它只会告诉您将'checkedCheckpoint'的状态设置为true,但此时它不会执行该命令。因此,基本上当您尝试设置localStorage变量时,它仍然是之前的状态。
尝试在这样的变量中设置新状态。
onChange (value){
var newState;
const { checkedCheckpoint } = this.state
if (value === 'checkpoint') {
if (checkedCheckpoint) {
newState = false;
console.log(newState);
}
else {
newState = true;
console.log(newState);
}
this.setState({checkedCheckpoint : newState});
localStorage.setObject('checkedCheckpoint', newState);
}
答案 3 :(得分:0)
也许,你可以这样做:
<Checkbox
checked={this.state.checkedCheckpoint}
onChange={() => this.setState((prevState) => ({checkedCheckpoint: !prevState.checkedCheckpoint}),
() =>{console.log(this.state.checkedCheckpoint)})}
>
</Checkbox>
此外,您的代码的问题在于它没有考虑到反应 setState异步发生的state
这一事实。因此,它会在记录时始终显示先前的状态。