React复选框以将字符串值传递给更新查询

huangapple go评论85阅读模式
英文:

react checkbox to pass a string value to update query

问题

这是我的代码:

import React, { Component } from "react";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";

import {
  setLastOrderDays,
  updateLastOrderAlert
} from "reducers/DealerPreferencesReducer";

class Alerts extends Component {
  state = {
    prevId: null,
    checked: 0
  };

  static getDerivedStateFromProps(props, state) {
    // 存储prevId以便在props变化时进行比较。
    // 清除以前加载的数据(以免呈现旧数据)。
    if (props.dealerID !== state.prevId) {
      return {
        prevId: props.dealerID
      };
    }

    // 不需要更新状态
    return null;
  }

  componentDidMount = () => {
    this.setState({ checked: this.props.preferences.last_order_alert_enabled ? 1 : 0 });
  };

  toggleAlerts = () => {
    this.props.actions.updateLastOrderAlert(
      this.props.preferences.id,
      this.props.dealerID,
      this.props.isGroup,
      this.props.preferences.last_order_alert,
      this.state.checked === 1
    );
  };

  handleCheck = event => {
    this.setState({ checked: event.target.checked ? 1 : 0 });
  };

  handleAlertDays = e => {
    e.persist();
    if (String(e.target.value) !== this.props.preferences.last_order_alert) {
      this.props.actions.updateLastOrderAlert(
        this.props.preferences.id,
        this.props.dealerID,
        this.props.isGroup,
        String(e.target.value),
        this.state.checked === 1
      );
    }
  };

  render = () => {
    const { preferences } = this.props;
    return (
      <div className="preferenceContainer">
        <div className="preferenceRow lg">
          <div className="preferenceLabelWrapper">
            <div className="preferenceLabel">Enable Alert</div>
            <div className="preferenceSubLabel">
              Toggles the Last Order Alert Email
            </div>
          </div>
          <div className="preferenceInput">
            <input
              type="checkbox"
              checked={this.state.checked === 1}
              onChange={this.handleCheck}
            />
          </div>
        </div>
        <div className="preferenceRow">
          <div className="preferenceLabelWrapper">
            <div className="preferenceLabel">Days Since Last Order</div>
          </div>
          <div className="preferenceInput">
            <input
              type="number"
              value={preferences.last_order_alert}
              onBlur={this.handleAlertDays}
              onChange={e =>
                this.props.actions.setLastOrderDays(e.target.value)
              }
              style={{ width: "50px" }}
            />
          </div>
        </div>
        <div className="preferenceRow">
          <button
            className="btn btn-primary"
            type="submit"
            onClick={this.toggleAlerts}
          >
            Save
          </button>
        </div>
      </div>
    );
  };
}

const mapStateToProps = state => ({
  dealerID: state.DealerTreeReducer.selectedShop.id,
  isGroup: state.DealerTreeReducer.selectedShop.folder,
  preferences: state.DealerPreferencesReducer,
  loading: state.DealerTreeReducer.loading
});

const mapDispatchToProps = dispatch => ({
  actions: bindActionCreators(
    { updateLastOrderAlert, setLastOrderDays },
    dispatch
  )
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(Alerts));

您想要的功能是每次点击复选框时都能获得1或0,然后将其传递给toggleAlerts以更新应用程序中用户的首选项。以上代码已经进行了相应的更改,现在复选框会在点击时立即更新状态,并在单击“保存”按钮时将更改应用到用户首选项。

英文:

This is my code:

import React, { Component } from &quot;react&quot;;
import { bindActionCreators } from &quot;redux&quot;;
import { connect } from &quot;react-redux&quot;;
import { withRouter } from &quot;react-router-dom&quot;;
import {
setLastOrderDays,
updateLastOrderAlert
} from &quot;reducers/DealerPreferencesReducer&quot;;
class Alerts extends Component {
state = {
prevId: null,
checked:  &quot;&quot;
};
static getDerivedStateFromProps(props, state) {
// Store prevId in state so we can compare when props change.
// Clear out previously-loaded data (so we don&#39;t render stale stuff).
if (props.dealerID !== state.prevId) {
//update action goes here...
//props.actions.getUsers(props.dealerID);
return {
prevId: props.dealerID
};
}
// No state update necessary
return null;
}
componentDidMount = () =&gt; {
this.setState({ days: this.props.preferences.last_order_alert });
//this.setState({ checked: this.props.preferences.last_order_alert_enabled})
};
toggleAlerts = e =&gt; {
//console.log(&#39;lastOrder&#39;, this.props.preferences.last_order_alert_enabled);
this.props.actions.updateLastOrderAlert(
this.props.preferences.id,
this.props.dealerID,
this.props.isGroup,
this.props.preferences.last_order_alert,
this.props.preferences.last_order_alert_enabled === this.handleCheck
);
};
handleCheck = event =&gt; {
console.log(&#39;called&#39;, this.setState);
this.setState({checked: event.target.checked})
};
handleAlertDays = e =&gt; {
e.persist();
if (String(e.target.value) !== this.props.preferences.last_order_alert) {
this.props.actions.updateLastOrderAlert(
this.props.preferences.id,
this.props.dealerID,
this.props.isGroup,
String(e.target.value),
this.props.preferences.last_order_alert_enabled
);
}
};
render = () =&gt; {
console.log(&#39;checked&#39;, this.state.checked);
const { preferences } = this.props;
return (
&lt;div className=&quot;preferenceContainer&quot;&gt;
&lt;div className=&quot;preferenceRow lg&quot;&gt;
&lt;div className=&quot;preferenceLabelWrapper&quot;&gt;
&lt;div className=&quot;preferenceLabel&quot;&gt;Enable Alert&lt;/div&gt;
&lt;div className=&quot;preferenceSubLabel&quot;&gt;
Toggles the Last Order Alert Email
&lt;/div&gt;
&lt;/div&gt;
&lt;div className=&quot;preferenceInput&quot;&gt;
&lt;input
type=&quot;checkbox&quot;
checked={this.state.checked}
onChange={this.handleCheck}
/&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div className=&quot;preferenceRow&quot;&gt;
&lt;div className=&quot;preferenceLabelWrapper&quot;&gt;
&lt;div className=&quot;preferenceLabel&quot;&gt;Days Since Last Order&lt;/div&gt;
&lt;/div&gt;
&lt;div className=&quot;preferenceInput&quot;&gt;
&lt;input
type=&quot;number&quot;
value={preferences.last_order_alert}
onBlur={this.handleAlertDays}
onChange={e =&gt;
this.props.actions.setLastOrderDays(e.target.value)
}
style={{ width: &quot;50px&quot; }}
/&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div className=&quot;preferenceRow&quot;&gt;
&lt;button
className={&#39;btn btn-primary&#39;}
type=&quot;submit&quot;
onClick={this.toggleAlerts}
&gt;Save
&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
);
};
}
const mapStateToProps = state =&gt; ({
dealerID: state.DealerTreeReducer.selectedShop.id,
isGroup: state.DealerTreeReducer.selectedShop.folder,
preferences: state.DealerPreferencesReducer,
loading: state.DealerTreeReducer.loading
});
const mapDispatchToProps = dispatch =&gt; ({
actions: bindActionCreators(
{ updateLastOrderAlert, setLastOrderDays },
dispatch
)
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(withRouter(Alerts));

What I am trying to do is that everytime I click the checkbox, I want to get either a one or a zero which in turn I will use to pass in to toggleAlerts to update the preferences of my user in my app. The checkbox right now only checks and unchecks. The only time it changes is when I hit the saved button. What I ultimately want to do is to be able to save the changes when I hit the save button. can anyone point me in the right direction?

答案1

得分: 0

修改您的handleCheck函数和setState以及在触发toggleAlerts时访问该状态变量,类似以下方式:

handleCheck = event => {
  console.log('called', this.setState);
  this.setState({ checked: Number(event.target.checked) }) // 在这里修改
};

toggleAlerts = e => {
  this.props.actions.updateLastOrderAlert(
    this.props.preferences.id,
    this.props.dealerID,
    this.props.isGroup,
    this.props.preferences.last_order_alert,
    this.props.preferences.last_order_alert_enabled === this.state.checked // 在这里修改
  );
};
英文:

modifying you're handleCheck function and setState that value and access that state variable while triggering toggleAlerts something like this.

handleCheck = event =&gt; {
console.log(&#39;called&#39;, this.setState);
this.setState({checked: Number(event.target.checked) }) //change here
};
toggleAlerts = e =&gt; {
this.props.actions.updateLastOrderAlert(
this.props.preferences.id,
this.props.dealerID,
this.props.isGroup,
this.props.preferences.last_order_alert,
this.props.preferences.last_order_alert_enabled === this.state.checked //change here
);
};

huangapple
  • 本文由 发表于 2020年1月6日 18:17:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/59610277.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定