gpt4 book ai didi

javascript - 与 React hooks 的 setState 回调等效

转载 作者:行者123 更新时间:2023-12-05 04:28:49 26 4
gpt4 key购买 nike

我有一个带有答案列表的模态。我可以点击一个答案来选择它,然后点击一个按钮来确认我的选择。或者我可以双击一个答案来选择它并确认。

我无法正确处理双击案例。

对于 React 类组件,我会像这样使用 setState() 的回调:

setState({selectedAnswer: answer}, confirm)

但是现在,我只弄清楚了以下内容:

const MyModal = ({hide, setAnwser}) => {
const [selectedAnswer, setSelectedAnswer] = useState(null);
const [isSelectionDone, setIsSelectionDone] = useState(false);

const confirm = () => {
if (!selectedAnswer) {
return;
}

setAnwser(selectedAnswer);
hide();
};

const handleAnswerOnClick = (answer) => {
setSelectedAnswer(answer);
};

const handleAnswerOnDoubleClick = (answer) => {
setSelectedAnswer(answer);
setIsSelectionDone(true);
};

useEffect(confirm, [isSelectionDone]);

return (
<div>
<div>{answers.map((answer) => <MyAnswer
isSelected={answer.id === selectedAnswer?.id}
key={answer.id}
answer={answer}
onClick={handleAnswerOnClick}
onDoubleClick={handleAnswerOnDoubleClick}/>)}</div>
<button onClick={confirm}>Confirm</button>
</div>
);
}

我强烈怀疑有更好/更好的方法。

也许很简单:

const MyModal = ({hide, setAnwser}) => {
const [selectedAnswer, setSelectedAnswer] = useState(null);

const confirm = () => {
if (!selectedAnswer) {
return;
}

setAnwser(selectedAnswer);
hide();
};

const handleAnswerOnClick = (answer) => {
setSelectedAnswer(answer);
};

const handleAnswerOnDoubleClick = (answer) => {
setAnwser(answer);
hide();
};

return (
<div>
<div>{answers.map((answer) => <MyAnswer
isSelected={answer.id === selectedAnswer?.id}
key={answer.id}
answer={answer}
onClick={handleAnswerOnClick}
onDoubleClick={handleAnswerOnDoubleClick}/>)}</div>
<button onClick={confirm}>Confirm</button>
</div>
);
}

哪种方式更好?

最佳答案

钩子(Hook)中没有类似的设置状态(设置状态后触发回调)。但是,您可以应用以下重构:

 const confirm = (sAnswer = selectedAnswer) => {
if (!sAnswer) {
return;
}

setAnwser(sAnswer);
hide();
};

然后

 const handleAnswerOnDoubleClick = (answer) => {
setSelectedAnswer(answer);
confirm(answer);
};

关于javascript - 与 React hooks 的 setState 回调等效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72517731/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com