我想把状态传递到一个对象中,因为之后我会发布一个API。我怎样才能把状态存储到对象中呢?如果我调用函数setAll()会导致一个无限循环。就像一个例子,console.log在控制台中返回无限次。
import React,{useState} from 'react';
import Signup1 from '../pages/Signup/steps/Signup1';
import Signup2 from '../pages/Signup/steps/Signup2';
import Signup3 from '../pages/Signup/steps/Signup3';
function Forms() {
const [alert,setAlert]=useState();
const [page,setPage] = useState(0);
const [formData,setFormData]= useState({
email :"",
FirstName:"",
LastName:"",
CountryNumber:"",
Number:"",
JobTitle:"",
People:"",
Company:"",
TaxID:""
})
const [email,setEmail] = useState("");
const [firstName,setFirstName] = useState("");
const [lastName,setLastName] = useState("");
const [countryNumber,setCountryNumber] = useState("");
const [number,setNumber] = useState("");
const [jobTitle,setJobTitle] = useState("");
const [people,setPeople] = useState("");
const [company,setCompany] = useState("");
const [taxID,setTaxID] = useState("");
const setAll = ()=>{
setFormData({
email :email,
FirstName:firstName,
LastName:lastName,
CountryNumber:countryNumber,
Number:number,
JobTitle:jobTitle,
People:people,
Company:company,
TaxID:taxID
})
console.log(formData)
}
const PageDisplay = () =>{
if(page===0){
return <Signup1
email={email}
setEmail={setEmail}
setPage={setPage}
/>;
}
if(page===1){
return <Signup2
firstName={firstName}
setFirstName={setFirstName}
lastName={lastName}
setLastName={setLastName}
countryNumber={countryNumber}
setCountryNumber={setCountryNumber}
number={number}
setNumber={setNumber}
jobTitle={jobTitle}
setJobTitle={setJobTitle}
setPage={setPage}/>;
}
if(page===2){
return <Signup3
people={people}
setPeople={setPeople}
company={company}
setCompany={setCompany}
taxID={taxID}
setTaxID={setTaxID}
page={page}
setPage={setPage}
/>
}
if(page===3){
return( <div>sucess</div>)
}
}
/*
if(page===3){
setAll()
return<div>sucess</div>
}
*/
return (
<div className='Forms'>
{PageDisplay()}
</div>
);
}
export default Forms;
1条答案
按热度按时间fhity93d1#
不要像这样调用
setAll()
,像这样设置状态的函数应该在事件发生时调用(如onClick
)或在useEffect
中,无论何时在组件主体中设置状态,组件都会重新呈现,从而触发另一个状态集,因此会导致无限循环,在您的情况下,最好在调用API时设置窗体主体。设置状态是一个代价高昂的操作,因此最好在调用API时最后设置窗体主体状态。