简体   繁体   English

在 react hook useState 的 set 参数中运行函数有什么缺点吗?

[英]Are there any disadvantages to running a function in react hook useState's set parameter?

I had a situation when I had to use the current values for further processing and couldn't rely on dependencies to update the function in time.我遇到了一种情况,我不得不使用当前值进行进一步处理,并且无法依靠依赖项及时更新函数。 I had to do something similar to the following.我不得不做类似于以下的事情。

const [values, setValues] = useState({});
const someCallback = useCallback(() => {
  setValues((values) => {
    if(values.x === 'something') return ({ ...values, x: 'something else' });
    return values;
  });
}, []);

It works for me but that doesn't mean its right.它对我有用,但这并不意味着它是正确的。 I've never seen anyone use it like above but I can't see anything wrong with above.我从未见过有人像上面那样使用它,但我看不出上面有什么问题。 Are there any disadvantages to using the useState's set parameter like this?像这样使用 useState 的 set 参数有什么缺点吗?

I don't see any problem with it.我看不出有什么问题。 You've declared that there are no dependencies, which is correct because you're using the callback version of setValues (and setValues , itself, is guaranteed to be stable).您已经声明没有依赖项,这是正确的,因为您使用的是setValues的回调版本(并且setValues本身保证稳定)。

The one minor thing I might do, which is more of a style thing and could be argued both ways, is I'd probably use a different name for the values parameter of the setValues callback, for clarity:我可能会做的一件小事,更像是一种风格,可以从两种方式进行争论,为了清楚起见,我可能会为setValues回调的values参数使用不同的名称:

const [values, setValues] = useState({});
const someCallback = useCallback(() => {
  setValues((currentValues) => {
    if(currentValues.x === 'something') return ({ ...currentValues, x: 'something else' });
    return currentValues;
  });
}, []);

But again, what you have seems fine.但同样,你所拥有的似乎很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM