检查所有状态值的更优雅的方式

贾登·沃克

有没有更优雅的方法来检查我的 React 应用程序中的所有状态变量?我的应用程序中目前有 14 个状态变量,我正在检查每个状态变量的值,如果它们未通过验证(左为空),则更新为空字符串代码如下:

  const [customerName, setCustomerName] = useState(null)
  const [customerPhone, setCustomerPhone] = useState(null)
  const [customerEmail, setCustomerEmail] = useState(null)
  const [customerAddress, setCustomerAddress] = useState(null)
  const [customerPostal, setCustomerPostal] = useState(null)
  const [purchasePrice, setPurchasePrice] = useState(null)
  const [colleagueName, setColleagueName] = useState(null)
  const [branch, setBranch] = useState(null)
  const [branchPhone, setBranchPhone] = useState(null)
  const [otherCompany, setOtherCompany] = useState(null)
  const [furtherInformation, setFurtherInformation] = useState(null)

 function submission() {
    if (customerName === null) {
        setCustomerName('')
    }
    if (customerPhone === null) {
        setCustomerPhone('')
    }
    if (customerEmail === null) {
      setCustomerEmail('')
    }
    if (customerAddress === null) {
      setCustomerAddress('')
    }
    if (customerPostal === null) {
      setCustomerPostal('')
    }
    if (purchasePrice === null) {
      setPurchasePrice('')
    }
    if (surveyType === null) {
      setSurveyType('')
    }
    if (colleagueName === null) {
      setColleagueName('')
    }
    if (branch === null) {
      setBranch('')
    }
    if (branchPhone === null) {
      setBranchPhone('')
    }
    if (company === null) {
      setCompany('')
    }
    if (company === 'Other' && otherCompany===null) {
      setCompany('Other')
      setOtherCompany('')
    }
    if (
      customerName !== ''
      && customerPhone !== ''
      && customerEmail !== ''
      && customerAddress !== ''
      && customerPostal !== ''
      && purchasePrice !== ''
      && surveyType !== ''
      && colleagueName !== ''
      && branch !== ''
      && branchPhone !== ''
      && company !== ''
      && otherCompany !== ''
    ){
      console.log('validation passed')
    }

  };

确实有效,所以它不是世界末日,但它似乎不是很优雅,我觉得那里可以有更简洁的补救措施?

谢谢

笨蛋

也许沿着这些路线的东西。由于所有这些状态变量似乎是紧密耦合的。我不明白为什么它们不能成为一个对象。

const [customer, setCustomer] = useState({
  customerName: '',
  customerPhone: '',
  customerEmail: '',
  customerAddress: '',
  customerPostal: '',
  purchasePrice: '',
  surveyType: '',
  colleagueName: '',
  branch: '',
  branchPhone: '',
  company: '',
  otherCompany: '',
})

const checksPasssed = Object.values(customer).every(v => v)

如果您需要更新其中之一,您可以使用传播。

setCustomer({...customer, company: 'yahoo'})

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章