[英]How to make one state change only after other state has been changed in functional component?
useEffect(() => {
if (!isEditing) {
setIsDialogOpen(false); // this happens first
}
}, [isEditing]);
useEffect(() => {
if (!isDialogOpen) {
setIsEditingTool(false); // this should happen second
}
}, [isDialogOpen]);
isEditing is a prop, coming from redux state. isEditing 是一个道具,来自 redux state。 The Dialog Title ("Add"/"Edit") Text is shown based on isEditingTool state (being set in the second useState).
对话框标题(“添加”/“编辑”)文本显示基于 isEditingTool state(在第二个 useState 中设置)。 The isEditing state should change only after the dialog has been closed, so that the text doesn't change before dialog close.
isEditing state 应仅在关闭对话框后更改,以便在对话框关闭之前文本不会更改。 I have tried a lot of options (setTimeout/usePrevious hook/useLayoutEffect), but its not working.
我尝试了很多选项(setTimeout/usePrevious hook/useLayoutEffect),但它不起作用。 Is there any way out, the only option left would be to make separate components, which I dont want.
有什么出路吗,剩下的唯一选择就是制作单独的组件,这是我不想要的。 Here I am using two states, setting isEditingTool only after dialog has been closed.
这里我使用了两种状态,只有在对话框关闭后才设置 isEditingTool。 there will be two different renders as per my understanding.
根据我的理解,会有两种不同的渲染。
I have implemented the solution here: https://codesandbox.io/s/frosty-fire-xz1pt?file=/src/App.js我在这里实现了解决方案: https://codesandbox.io/s/frosty-fire-xz1pt?file=/src/App.js
With hooks, we can update one state after updating another state by using useEffect.使用钩子,我们可以在使用 useEffect 更新另一个 state 之后更新一个 state。
export default function App() {
const [text1, setText1] = useState("");
const [text2, setText2] = useState("");
// update text2, when text1 updates
useEffect(() => {
if (text1) {
setText2(`${text1}, then this is text 2`);
}
}, [text1]);
return (
<div className="App">
<h1>useState callback</h1>
<h3>{text1}</h3>
<h4>{text2}</h4>
<button onClick={() => setText1("this is text 1")}>Click This</button>
</div>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.