首页 > 解决方案 > React,Redux Form:更改处理程序不允许以任何方式翻转传递的参数

问题描述

我最近遇到了一个很奇怪的问题。我在 react 中有一个使用 redux 形式的类组件。onChange如果输入复选框被切换,则调用事件处理程序。两个参数valuetype(输入名称)被传递给事件处理程序。当我控制台日志时,value它正确显示了以前的值。但是,我不能以任何方式翻转这个布尔值,即表达式!valuelet 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);

输出(切换两次:检查初始状态)

控制台输出

标签: javascriptreactjsredux-form

解决方案


您没有设置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})
}

推荐阅读