javascript - React,Redux Form:更改处理程序不允许以任何方式翻转传递的参数
问题描述
我最近遇到了一个很奇怪的问题。我在 react 中有一个使用 redux 形式的类组件。onChange
如果输入复选框被切换,则调用事件处理程序。两个参数value
和type
(输入名称)被传递给事件处理程序。当我控制台日志时,value
它正确显示了以前的值。但是,我不能以任何方式翻转这个布尔值,即表达式!value
或let value = value?false:true
总是根据初始状态返回真/假,而与当前状态无关。我在 google & SO 上搜索以找到原因,但找不到相同的原因。任何形式的帮助都深表感谢。
这是供您参考的代码
class Example extends Component {
constructor(props){
super(props);
this.state = {
name: true
};
this.handleChange = this.handleChange.bind(this);
};
handleChange(value, type) {
console.log(value); //outputs previous value (before toggle)
let currValue = value ? false:true; //this line is not working
console.log(currValue); //outputs the same value (irrespective of state)
}
render() {
return (
<div>
<Field component="input" type="checkbox" name="name" id="name"
onChange={({target}) => this.handleChange(target.value,target.name)}/> Name
</div>
);
}
}
function mapStateToProps(state) {
return state;
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({change},dispatch);
}
export default compose(
reduxForm({
form: 'example', key: 'example',
initialValues: {
name: true
},
enableReinitialize: true
}),
connect(mapStateToProps, mapDispatchToProps)
)(Example);
输出(切换两次:检查初始状态)
解决方案
您没有设置Field
. 因此,您需要设置值:
<Field
component="input"
type="checkbox"
name="name"
id="name"
onChange={({target}) => this.handleChange(target.value,target.name)}
value={this.state.name || true}
/>
处理程序:
handleChange(value, type) {
this.setState({[type]: !value})
}
推荐阅读
- python-3.x - 如何从 Dataframe 中删除 \c?
- node.js - 如何使用转换流来验证 Node.js 中的数据?
- git - 将 JSON 集合文件从 CR LF (Windows) 导出到 LF (Unix) 时邮递员更改行尾
- python - Selenium 等待 javascript 超时
- flutter - 我如何使用rest api在flutter中只获取文本
- flutter - BlocBuilder 小部件的 Flutter 小部件测试
- postgresql - 使用 macOS Big Sur(M1) 安装 PostgreSQL 失败
- python-3.x - 在 S3 中上传对象时添加加密
- c++ - C++ API 设计模式
- ios - 如何在 SwiftUI 中更改步进器的背景颜色?