【发布时间】:2017-09-14 13:28:46
【问题描述】:
我想在每次将复选框切换为 true 时更新数组。使用此当前代码,如果我单击一个复选框,它将记录它是错误的。即使我刚刚更新了状态。 setState 是否只需要一些时间,例如 API 调用?这对我来说没有意义。
import React, {Component} from 'react';
class Person extends Component {
constructor(props) {
super(props);
this.state = {
boxIsChecked: false
};
this.checkboxToggle = this.checkboxToggle.bind(this);
}
checkboxToggle() {
// state is updated first
this.setState({ boxIsChecked: !this.state.boxIsChecked });
console.log("boxIsChecked: " + this.state.boxIsChecked);
if (this.state.boxIsChecked === false) {
console.log("box is false. should do nothing.");
}
else if (this.state.boxIsChecked === true) {
console.log("box is true. should be added.");
this.props.setForDelete(this.props.person._id);
}
}
render() {
return (
<div>
<input type="checkbox" name="person" checked={this.state.boxIsChecked} onClick={this.checkboxToggle} />
{this.props.person.name} ({this.props.person.age})
</div>
);
}
}
export default Person;
我尝试过 onChange 而不是 onClick。我觉得我已经在遵循我从here 和here 阅读的关于基本组件公式的建议。我将 Redux 用于其他值会影响任何事情吗?有没有办法只读取复选框是什么,而不是试图控制它? (复选框本身工作正常,并且 DOM 会更新它是否被选中。)
【问题讨论】:
-
您的代码 sn-p 根本没有使用 Redux。它正在使用常规的 React 状态。
-
是的,我只是在检查是否存在可能导致某些问题的副作用。我也在组件中使用了一些 Redux 操作。
标签: javascript reactjs checkbox redux react-redux