我试图在不创建大量嵌套 if 语句的情况下进行条件形式输出。 这些是表单正在更改的关键代码。
class MasterForm extends React.Component {
constructor(props) {
super(props)
this.state = {
currentStep: 1,
notice: 'No',
delay: 'No',
qualifying: 'Enter Days Here',
onegreater: 'Other',
days_28: 'No',
EoTClaim: 'No',
EoTdate : 'No',
EoTEvidence : 'No'
}
}
handleChange = event => {
const {name, value} = event.target
this.setState({
[name]: value
})
}
handleSubmit = event => {
event.preventDefault()
const { notice, delay, qualifying, onegreater, days_28, EoTClaim, EoTdate, EoTEvidence } = this.state
const _MS_PER_DAY = 1000 * 60 * 60 * 24;
// a and b are javascript Date objects
function dateDiffInDays(a, b) {
// Discard the time and time-zone information.
const utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return Math.floor((utc2 - utc1) / _MS_PER_DAY);
}
// test it
const a = new Date(days_28),
b = new Date(EoTdate),
difference = dateDiffInDays(a, b);
function claimGranted(){
return notice === 'Yes'
&& delay === 'Yes'
&& onegreater !== 'Other'
&& EoTClaim === 'Yes'
&& EoTEvidence === 'Yes'
&& difference < 28;
}
function Fail_text(notice, delay, onegreater, EoTClaim, EoTEvidence, difference){
var fail = "The Contractor is not entitled to an Extension of Time because: \n"
if (notice === "No") {
t_n = "You did not receive prompt written notice of this delay event \n ";
} else {t_n = "Nothing"}
/*var t_n = (notice === "No") ? "":"You did not receive prompt written notice of this delay event \n "*/ //etc
return alert(fail+t_n+t_d+t_o+t_Eot+t_eE+t_dif)
}
if (claimGranted()) {
alert(`Claim Granted: The contractor is entitled to an Extension of Time of ${qualifying} days.`);
} else Fail_text();
}
/* This result varies depending on which requirement is not satisfied and can either have only 1 reason or multiple reasons.
例如 如果只有问题 1 是红色答案,则应为: 您没有收到有关此延误事件的及时书面通知”
*/
我解决这个问题的方法是,
创建双重函数来回答每种类型的提交。
目前已经解决了这个问题 - 感谢您的帮助,虽然它没有解决最初的问题,但它确实引导我清理了我的代码。
提前致谢,
最佳答案
开关在这里帮不了你。开关适用于单个变量有多个可能值并且您希望以不同方式处理每个值的情况。您可以通过添加辅助函数来检查声明是否被授予并在条件中调用该函数,从而使此代码更具可读性。这只是下面的一个基本示例,您还可以将其添加为组件类上的方法(假设这是来自基于对 this.state
的引用的 React 应用程序)。
function claimGranted(){
return this.state.notice === 'Yes'
&& this.state.delay === 'Yes'
&& this.state.onegreater !== 'Other'
&& this.state.EoTClaim === 'Yes'
&& this.state.EoTEvidence === 'Yes'
&& this.state.difference < 28;
}
if (claimGranted()) {
alert(`Claim Granted: The contractor is entitled to an Extension of Time of ${qualifying} days.`);
} else {
alert(`The Contractor is not entitled to an Extension of Time because: You did not receive prompt written notice of this delay event`);
}
关于javascript - 条件形式输出 - 使用 react 形式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57941296/