gpt4 book ai didi

javascript - React State 未更新并重置为原始状态

转载 作者:行者123 更新时间:2023-11-30 08:24:41 25 4
gpt4 key购买 nike

我在这里面临一个非常奇怪的问题。我正在使用react-toggle依赖项来返回某些输入的真/假值。

基本上我正在做的是使用react-toggle输入的回调函数来更新我的react状态的值。由于某种原因,它只会更新最后一个已更改的输入,其他输入将变为 false。

这是我的代码的外观:

RandomComponent.js

<ToggleComponent title="TestA"/>
<ToggleComponent title="TestB"/>
<ToggleComponent title="TestC"/>
<ToggleComponent title="TestD"/>

ToggleComponent.js

constructor(props){
super(props);
this.state={
testA:false,
testB:false,
testC:false,
testD:false,
}
}
updateCheckValue(title){
if(title === 'TestA'){
this.setState({
testA: !this.state.testA
}, ()=>{
console.log(this.state)
})
}
if(title === 'TestB'){
this.setState({
testB: !this.state.testB
}, ()=>{
console.log(this.state)
})
}
if(title === 'TestC'){
this.setState({
testC: !this.state.testC
}, ()=>{
console.log(this.state)
})
}
if(title === 'TestD'){
this.setState({
testD: !this.state.testD
}, ()=>{
console.log(this.state)
})
}
}

render(){
return(
<Row className={styles.container}>
<Col sm={1} md={1} lg={1}></Col>
<Col sm={2} md={2} lg={2}>
<Toggle
onChange={this.updateCheckValue.bind(this, this.props.title)}
icons={false} />
</Col>
<Col sm={8} md={8} lg={8}>
<h4>{this.props.title}</h4>
</Col>
<Col sm={1} md={1} lg={1}></Col>
</Row>
)
}

最佳答案

你应该改变这里的方法,状态应该由RandomComponent.js管理,ToggleComponent.js应该在每次调用时调用回调。结果应该是这样的:RandomComponent.js

constructor(props){
super(props);
this.state={
testA:false,
testB:false,
testC:false,
testD:false,
}
}
updateCheckValue(att){
this.setState({
[att]: !this.state[att]
}, ()=>{
console.log(this.state)
})
}
}

render(){
<ToggleComponent title="TestA" onToggle={() => this.updateCheckValue("testA")}/>
<ToggleComponent title="TestB" onToggle={() => this.updateCheckValue("testB")/>
<ToggleComponent title="TestC" onToggle={() => this.updateCheckValue("testC")/>
<ToggleComponent title="TestD" onToggle={() => this.updateCheckValue("testD")/>
}

ToggleComponent.js

<Row className={styles.container}>
<Col sm={1} md={1} lg={1}></Col>
<Col sm={2} md={2} lg={2}>
<Toggle
onChange={this.props.onToggle}
icons={false} />
</Col>
<Col sm={8} md={8} lg={8}>
<h4>{this.props.title}</h4>
</Col>
<Col sm={1} md={1} lg={1}></Col>
</Row>

关于javascript - React State 未更新并重置为原始状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47513829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com