使用mapstatetoprops和mapdispatchtoprops时如何清除错误?

时间:2018-12-10 15:52:13

标签: reactjs react-redux

我有一个表单,用户正在尝试将车辆添加到数据库中。当给出错误并且用户无法添加车辆时,页面上会显示错误。

我有一个重置按钮。此按钮清除表单中的项目,但仍显示错误消息。我希望用户按下重置按钮时错误消息消失。我该怎么做?

class VehiclePage extends React.Component {
  defaultState = {errors: [], tag: null, vin: null, location: null, message: null, msg: null};

  constructor(props) {
    super(props);

    this.state = this.defaultState;
    this.submitVehicle = this.submitVehicle.bind(this);
    this.resetFromState = this.resetFromState.bind(this);
    this.validateForm = this.validateForm.bind(this);

  }

  resetFromState = () => {
    this.setState({
      ...this.defaultState
    });
    this.emptyArray();
  }

  emptyArray() {
    const errors = [];
    return errors;
  }

  validateForm(tag, vin, location) {
    const errors = [];
    if (tag == '') {
      errors.push("Please enter vehicle's RFIDTAG.");
    } else if (vin == '') {
      errors.push("Please enter the vehicle's VIN.");
    } else if (vin.length < 17) {
      errors.push("VIN must be longer than 17 characters.");
    } else if (location == '') {
      errors.push("Please enter vehicle's location.");
    }
    return errors;
  }

  submitVehicle(tag, vin, location) {
    let msg;
    let errors = this.validateForm(tag, vin, location);
    msg = "HI";


    if (errors.length > 0) {
      this.setState({errors: errors});
      console.log("error: ", errors);
      return;
    } else {
      // errors=this.emptyArray();

      this.setState({errors: []});
      var input = {
        rfidtag: tag,
        vin: vin,
        vehzone: location
      };
      //console.log("the object is: ", input);
      //msg="MADE IT";
      console.log("MESSAGE: ", msg);
      this.props.createVehicle(input);


      if (this.props.message != '') {
        console.log("SERVER ERROR!!!");
        //msg="Could not enter into system.";
      }
      //console.log("this message: ", this.props.message.state);
    }
  }

  render() {
    const {errors} = this.state;
    const {msg} = this.state;

    return (
      <div>
        <AddVehicle submitVehicle={this.submitVehicle} resetFromState={this.resetFromState}/>
        <div><font color="red">{errors}</font></div>
        <h4>{this.props.message}</h4>
        <h3>{this.state.msg}</h3>
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => {
  console.log("state in vehicle page is: ", state);

  return {
    vehicle: state.vehicle,
    message: state.vehicleReducer.message,
    error: state.vehicleReducer.error
  }
};

const mapDispatchToProps = (dispatch) => {
  return {
    createVehicle: vehicle =>
      dispatch(vehicleActions.createVehicle(vehicle))
  }
};

export default connect(mapStateToProps, mapDispatchToProps)(VehiclePage);

0 个答案:

没有答案