问题描述
export function useShape (){
const [state, setState] = useState({
shape: 'square',
size: {
width: 100,
height: 100
}
})
// Change shape name while size update
useEffect(()=>{
const {size: {width, height}} = state
setState({
...state,
shape: width===height ? 'square' : 'rect'
})
}, [state, state.size])
}
预期
当尺寸更新时,副作用会根据宽度、高度改变尺寸名称.
Expected
When size updated, the side effect will change the size name based on width,height.
目标是让状态保持一致,所以无论大小如何变化,我都会得到正确的形状.
The goal is to make state consistent, so I will always get the correct shape no matter how size changes.
useEffect 函数陷入了循环,如果我去掉'state' 依赖就好了,但是intelliSense 请求了'state' 依赖,那么解决方案是什么?
The useEffect function got into a loop, if I remove the 'state' dependence it will be good, but the intelliSense requested 'state' dependence, so what's the solution?
推荐答案
您可以查看这个 沙盒链接 解决方案
You can check out this sandbox link for the solution
无限循环是由于放置了状态"在 useEffect 中修改状态本身时作为依赖项.
The infinite loop is due to placing "state" as a dependency while modifying the state itself in useEffect.
解决方案是通过将视图变量与受控变量分开来分离状态.
The solution is to decouple your state, by keeping your view variable separate from your controlled variables.
这是定义 useShape 钩子的方式.
this is how you can define your useShape hook.
function useShape() {
const [shape, setShape] = useState("square");
const [dimension, setDimension] = useState({
width: 100,
height: 100
});
// Change shape name while size update
useEffect(() => {
const { height, width } = dimension;
setShape(height === width ? "square" : "react");
}, [dimension, dimension.height, dimension.width]);
return [shape, setDimension];
}
通过这种方式,您可以公开 Dimension setter,并将变量视为独立的 Pieces.
this way you can expose your Dimension setter, and you view variable as independent Pieces.
这篇关于React useEffect 如何观察和更新状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!