简体   繁体   English

“TypeError:无法读取未定义的属性(读取‘id’)”

[英]"TypeError: Cannot read properties of undefined (reading 'id')"

I'm building the website but I got error in the browser's console, what's the problem and how to fix it.我正在构建网站,但在浏览器的控制台中出现错误,问题是什么以及如何解决。 And another promblem is I can not get value from first and second select but input is fine.另一个问题是我无法从第一个和第二个select获得价值,但input没问题。

Here's the code.这是代码。

const Refund = () => {
  const [payment, setPayment] = useState({
    rpayment: ""
  });

  const [reason, setReason] = useState({
    rrefund: ""
  });

  const [date, setDate] = useState({
    ddate: ""
  });

  const handleInputOnChange = ({ currentTarget: select, input}) => {
    const tempPayment = {...payment};
    tempPayment[select.id] = select.value;
    setPayment(tempPayment);
    console.log(tempPayment)

    const tempReason = {...reason};
    tempReason[select.id] = select.value;
    setReason(tempReason);
    console.log(tempReason)

    const tempDate = {...date};
    tempDate[input.id] = input.value;
    setDate(tempDate);
    console.log(tempDate)
  };

  return (
    <div className="refund">
      
    <fieldset className="refund__container">
        <legend align="center">
        </legend>
        <form className="refund__form">
          <div className="refund__form__container">
            <div className="refund__form__item" >
              <select name="rpayment" id="rpayment" value={payment["rpayment"]} onChange={handleInputOnChange}>
                <option value="none" selected disabled hidden>ช่องทางการรับเงิน</option>
                <option value={payment["rpayment"]}>Credit Card</option>
                <option value={payment["rpayment"]}>Paypal</option>
                <option value={payment["rpayment"]}>Wallet</option>
              </select>
            </div>
            <div className="refund__form__item">
                <input
                 type="date" 
                 id="rdate" 
                 name="rdate"
                 value={reason["ddate"]}
                 onChange={handleInputOnChange}
                 />
            </div>
            <div className="refund__form__item">
              <select name="reason" id="reason" value={reason["rrefund"]} onChange={handleInputOnChange}>
                <option value="none" selected disabled hidden>เหตุผลที่ต้องการเงินคืน</option>
                <option value={reason["rrefund"]}>I need to cancle</option>
                <option value={reason["rrefund"]}>It's not comfortable</option>
                <option value={reason["rrefund"]}>Too expensive</option>
              </select>
            </div>
          </div>
        </form>
        <input type="submit" className="refund__btn" value="Submit" />
      </fieldset>
  </div>
  )
}

export default Refund;

Thank you in advance!!先感谢您!!

There's such a huge amount of problems that I don't even know which one to start from.有这么多问题,我什至不知道从哪一个开始。

Well let's start with state. One state is enough.好吧,让我们从 state 开始吧。一个 state 就足够了。

const [formState, setFormState] = useState({
 rpayment: "none", // refers to paymentMethods items
 rrefund: "expensive", // refers to refundReasons value field
 ddate: "" // here's input string
})

Second - selects and their change handlers.第二 - 选择及其更改处理程序。

// simple approach
const paymentMethods = ['none', 'Credit', 'Paypal', 'Wallet'];

// complex approach
const refundReasons = [
 {
   title: 'I need to cancle',
   value: 'need'
 },
 {
   title: 'Too expensive',
   value: 'expensive'
 }
 // add some more
]

Select handler. Select 处理程序。 Here we are currying function and returning a new one with enclosed stateFieldName referring to our composed state field.在这里,我们柯里化 function 并返回一个新的,其中包含stateFieldName引用我们组合的 state 字段。 But I'm not actually sure if we must use event.target or event.currentTarget - try both, one will work for sure.但我实际上不确定我们是否必须使用event.targetevent.currentTarget - 尝试两者,一个肯定会起作用。

const selectHandler = (stateFieldName) => (event) => {
 setFormState({
   ...formState,
   [stateFieldName]: event.currentTarget.value

 })
}

Render selects (no styles, sorry)渲染选择(没有 styles,抱歉)

// no need to apply hidden fields
<select
  onChange={selectHandler('rpayment')} // yes, this is a function call, it returns a new function
>
{paymentMethods.map((item) => (
  <option
    key={item}
    value={item}
    selected={item === formState.rpayment}
  >
   {item}
  </option>
))
}
</select>

// complex select

<select
  onChange={selectHandler('rrefund')}
>
{refundReasons.map(({title, value}) => (
  <option
    key={value}
    value={value}
    selected={value === formState.rrefund}
  >
   {title}
  </option>
))}
</select>


// input
<input
  type="date" 
  value={formState.ddate}
  onChange={selectHandler(ddate)} // probably this handler will work here too
/>

And finally submit button.最后提交按钮。 If your form is supposed to send async request, your submit button doesn't need value prop and any handler.如果您的表单应该发送异步请求,则您的提交按钮不需要value prop 和任何处理程序。 I general it must have type='submit' prop but the form itself must have a submit hander and send data stored in your state.我一般它必须有type='submit'属性,但form本身必须有一个提交处理程序并发送存储在您的 state 中的数据。

Something like就像是

<form
  onSubmit={() => {
    axios.post('/some/api', {
      data: formState
    })
    .then(/* you logic here */)
  }}
>
// your inputs here
</form>

Sorry for approximations and possible mistakes, I hope you got the main idea.对于近似值和可能的错误,我深表歉意,我希望你明白了主要思想。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeError:无法读取未定义的属性(读取“_id”) - TypeError: Cannot read properties of undefined (reading '_id') 类型错误:无法在 React 中读取未定义(读取“id”)的属性 - TypeError: Cannot read properties of undefined (reading 'id') in React 未捕获的类型错误:无法读取未定义的属性(读取“id”) - Uncaught TypeError: Cannot read properties of undefined (reading 'id') Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id') - Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'id') TypeError:无法读取未定义(读取“_id”)购物车添加的属性 - TypeError: Cannot read properties of undefined (reading '_id') cart add 类型错误:无法读取未定义的属性(读取“createdTimestamp”) - TypeError: Cannot read properties of undefined (reading 'createdTimestamp') TypeError:无法读取未定义的属性(读取“forEach”) - TypeError: Cannot read properties of undefined (reading 'forEach') TypeError:无法读取未定义的属性(读取“学生”) - TypeError: Cannot read properties of undefined (reading 'students') TypeError:无法读取未定义的属性(读取“addEventListener”) - TypeError: Cannot read properties of undefined (reading 'addEventListener') TypeError:无法读取未定义的属性(读取&#39;indexOf&#39;) - TypeError: Cannot read properties of undefined (reading 'indexOf')
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM