這是設定:
在 App.js 中,我有每個步驟的路線。我有一個主要物件,當使用道具進行步驟時,我會在其中更新值。
這是我的物件:
const [postData, setPostData2] = useState({
'meta': {
"originally_created": todaysDate,
"user_agent": navigator.userAgent,
"ip_address": ip,
"tcpa_compliant": true,
"tcpa_consent_text": "By clicking Get My Free Quote below, I am agreeing to receive text messages from InsurTech Groups and business partners. I provide my signature expressly consenting to recurring contact from InsurTech Groups or its business partners at the number I provided regarding products or services via live, automated or prerecorded telephone call, text message, or email. I understand that my telephone company may impose charges on me for these contacts, and I am not required to enter into this agreement as a condition of purchasing property, goods, or services. I understand that I can revoke this consent at any time. Terms & conditions & Privacy policy apply.",
"landing_page_url": ""
},
"contact": {
"first_name": "",
"last_name": "",
"email": "",
"phone": "",
"address": "",
"city": "",
"state": "",
"zip_code": "",
"ip_address": ip,
},
"data": {
"drivers": [
{
"first_name": "",
"last_name": "",
"birth_date": "",
"gender": "",
},
{
"first_name": "",
"last_name": "",
"birth_date": "",
"gender": "",
}
],
"vehicles": [{
"year": "",
"make": "",
"model": "",
},
{
"year": "",
"make": "",
"model": "",
}
],
"requested_policy": {
"coverage_type": "",
},
"current_policy": {
"insurance_company": "",
}
}
});
這是一些邏輯,因此我可以使用道具更新物件:
useEffect(() => {
const stringifiedData = sessionStorage.getItem('main-form-data')
if (stringifiedData) {
const jsonData = JSON.parse(stringifiedData);
setPostData(jsonData);
}
}, []);
useEffect(() => {
sessionStorage.setItem('main-form-data', JSON.stringify(postData));
}, [JSON.stringify(postData)]);
const setPostData = (obj) => {
console.log('in app state', obj);
setPostData2(obj)
}
const setPostDataForPage = (data) => {
setPostData({ ...postData, ...data });
}
這就是我將它傳遞到每條路線的方式:
<Route
path="/car-year"
element={<CarYear setPostData={setPostDataForPage} />}
/>
<Route
path="/car-make"
element={<CarMake setPostData={setPostDataForPage} />}
/>
<Route
path="/car-model"
element={<CarModel setPostData={setPostDataForPage} />}
/>
所以這里是問題:
當我更新汽車年、汽車制造商和汽車型號時,它會按預期在控制臺日志中更新,但每次控制臺日志時,它都會完全覆寫先前的物件。
例子:
年步:
....rest of console log from object
vehicels: year: 1991
進行步驟:
....rest of console log from object
vehicels: make: Honda
如您所見,它剛剛寫完年份并用品牌替換它
以下是我在每個步驟中的更新方式:
車年道具更新:
props.setPostData({
vehicles:
{
year: year,
}
})
汽車制造道具更新:
props.setPostData({
vehicles: [
{
make: make,
}
]
})
為什么會這樣,我該如何解決?
這是一個*額外的問題大聲笑,如果我有兩輛車,我如何確保當人進入第二輛車時它不會覆寫第一輛車的資料!
我知道這個超級長,提前謝謝你!!!!<3
uj5u.com熱心網友回復:
您在設定器中傳播原始狀態。React 不會同步地改變狀態,所以你結束在原始狀態上呼叫所有 3 個設定器。
要使用實際狀態,請將回呼傳遞給狀態設定器,并將前一個狀態作為引數。
const setPostDataForPage = (data) => {
setPostData(prevData => { ...prevData, ...data });
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/522450.html
下一篇:ASP.NET分頁重置為多個表單
