3 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超10個(gè)贊
一種方法是制作一個(gè)函數(shù),給定步長增量計(jì)數(shù)和一個(gè)與現(xiàn)有狀態(tài)合并的新對象,調(diào)用setInputValue所需的組合對象:
const setStep = (newProps, stepIncrement) => {
setInputValue((prevState) => ({
...prevState,
...newProps,
step: prevState.step + stepIncrement,
}));
};
然后代替firstStep(firstName, lastName),你可以做setStep({ firstName, lastName }, 1),等等。
由于您使用的是掛鉤,另一種選擇是使用單獨(dú)的狀態(tài)變量和函數(shù):
const [step, setStep] = useState(1);
const [firstName, setFirstName] = useState('');
// etc
const firstStep = (firstName, lastName) => {
setFirstName(firstName);
setLastName(lastName);
setStep(step + 1);
};
const secondStep = (email, password) => {
setEmail(email);
setPassword(password);
setStep(step + 1);
};
const thirdStep = () => setStep(step + 1);
const fourthStep = () => setStep(step + 2);

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊
在我看來
const step = ({ firstName = "", lastName = "", email = "", password = "", step = 0 }) => {
setInputValue(prevState => ({
...prevState,
step: prevState.step + step,
firstName: firstName || prevState.lastName,
lastName: lastName || prevState.lastName,
email: email || prevState.email,
password: password || prevState.password
}));
};
添加回答
舉報(bào)