【问题标题】:changing the value of one object to true or false in redux在 redux 中将一个对象的值更改为 true 或 false
【发布时间】:2017-03-02 16:19:50
【问题描述】:

我正在尝试更改 redux 中复选框的状态。除了最后一部分,一切都设置正确。我尝试发送“假”或“真”并决定实际调用什么,但我收到此错误

Uncaught TypeError: Cannot read property 'payload' of undefined

这是我的代码

export function isChecked(isCheck) {

if(isCheck == false){
    return{
        type: "IS_TRUE",
        isCheck
    }
} else if (isCheck == true){
    return{
        type: "IS_FALSE",
        isCheck
    }
  }
}

如果我只放 else 那么它可以正常工作,但第二次它不会改变

【问题讨论】:

    标签: javascript reactjs ecmascript-6 redux react-redux


    【解决方案1】:

    你用错了redux,这里是checkbox的例子:

    // action
    
    export const SET_CHECKBOX_VALUE = 'SET_CHECKBOX_VALUE ';
    export function setChecked(checked) {
     return {
       type: SET_CHECKBOX_VALUE,
       checked
     }
    }
    
    // filter/Reducer
    
    import { SET_CHECKBOX_VALUE } from '..your action file here';
    
    const initialCheckboxState = { isChecked: false };
    
    export default function checkBoxFilter(state, action) {
      switch (action.type) {
        case SET_CHECKBOX_VALUE :
          return { checked: action.checked}
        default:
          return initialCheckboxState;
      }
    }
    
    // component
    import React, { Component } from 'react';
    import { bindActionCreators } from 'redux';
    import { connect } from 'react-redux';
    
    import * as checkBoxActions from '..your action file here';
    
    class MyComponent extends Component {
    
      static propTypes = {
        isChecked: React.PropTypes.bool.isRequired,
        setChecked: React.PropTypes.func.isRequired
      };
    
      render() {
        return (
          <div onClick={() => { this.props.setChecked(!this.props.isChecked) }>
            {this.props.isChecked}
          </div>
        );
      }
    }
    
    function mapStateToProps(state) {
      return {
        isChecked: state.checkBoxFilter.checked
      };
    }
    
    function mapDispatchToProps(dispatch) {
      return bindActionCreators(checkBoxActions, dispatch);
    }
    
    export default connect(mapStateToProps, mapDispatchToProps)(MyComponent);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2011-01-18
      • 1970-01-01
      • 2022-10-05
      • 2023-03-08
      • 2017-11-05
      相关资源
      最近更新 更多