已解決 謝謝您的幫助
我正在設定組件的道具
<Component myprops={state_variable}/>
問題是,當我創建組件并設定道具時,狀態變數還不存在并且我的代碼中斷了。我能做些什么來解決這個問題?此外,當我更改狀態時,道具不會更新。
<ServiceTicket
showOverlay={Tickets_disabled_withError[ticket_num]?.isDisabled}
showSelectedError={Tickets_disabled_withError[ticket_num]?.showError}
/>
我的初始狀態初始變數:
const [Tickets_disabled_withError,setTickets_disabled_withError] = useState({})
我正在嘗試呼叫將更新狀態并更改道具等于的值的函式。
const OverLayOnAll = (enable) =>
{
let tempobject = Tickets_disabled_withError
for (let key in tempobject)
{
if (enable == "true")
{
tempobject[key].isDisabled = true
}
else if (enable == "false")
{
tempobject[key].isDisabled = false
}
}
setTickets_disabled_withError(tempobject)
}
我解決了這個問題。非常感謝你的幫助。我必須設定使用可選鏈接?并重新渲染組件。
uj5u.com熱心網友回復:
值存在。只是價值本身就是undefined. 定義狀態時需要設定一個初始值
const [statevariable, setstatevariable] = useState({
somekey: {
isDisabled: false // or whatever the initial value should be
}
}) // or whatever else you need it to be
對于第二個問題,您使用的是相同的指標。JavaScript 通過參考實作相等。您已經轉換了現有值,因此 React 不會檢測到更改。解決此問題的最簡單方法是在開始轉換之前創建一個淺拷貝
let tempobject = {...Tickets_disabled_withError}
uj5u.com熱心網友回復:
你的問題我不是很清楚,但你的setTickets_disabled_withError電話有問題。
當您ticketsDisabledWithError使用之前的值更新狀態屬性 ( ) 時,您需要使用回呼引數。
(見https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous)
overlayAll = (enable)=> {
setTicketsDisabledWithError((ticketsDisabledWithError)=> {
return Object.keys(ticketsDisabledWithError).reduce((acc,key)=> {
acc[key].isDisabled = (enabled=="true");
return acc;
}, {}); // initial value of reduce acc is empty object
})
}
另外,請學習 JS變數命名約定。它會幫助你和那些試圖幫助你的人。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/495082.html
標籤:javascript 反应
下一篇:簡化自動建議的設計
