React Hooks:为什么将设置状态函数传递给子组件是不好的做法? [英] React Hooks : Why is it bad practice to pass the set state funcitons to a Child Component?

查看:77
本文介绍了React Hooks:为什么将设置状态函数传递给子组件是不好的做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题来提高我对 React 钩子的理解.它说,如果将设置的状态函数或钩子传递给孩子,这是不好的做法.所以应该只将一个处理函数传递给位于父级中的子级,然后在那里使用设置状态函数.当我在开发应用程序的许多工作部分后遇到这个问题时,我想知道为什么必须避免这种情况,因为它对我来说效果很好.

I have a question to improve my comprehension of react hooks. Its said that if one passes the set state functions or hooks to the children its bad practice. So one should just pass a handler function to the child which is located in the parent and then uses the set state functions in there. As I came across this after developing many working parts of an application I would like to know why this has to be avoided as it worked fine for me.

我希望你们在没有代码示例的情况下理解我的问题,如果我需要澄清,我会提供一些片段.

I hope you guys understand my issue without code examples, if I need to clarify I would ofc provide some snippets.

提前致谢!

推荐答案

将状态 setter 函数传递给孩子是一种不错的做法,这是完全可以接受的.事实上,我认为这样做:

It isn't bad practice to pass a state setter function to a child, this is totally acceptable. In fact, I would argue that doing this:

const MyComponent = () => {
  const [state, setState] = useState();

  return <Child onStateChange={setState} />
}

const Child = React.memo(() => {...});

const MyComponent = () => {
  const [state, setState] = useState();

  return <Child onStateChange={(value) => setState(value)} />
}

const Child = React.memo(() => {...});

因为在第一个示例中,每当 MyComponent 呈现时,都不会重新呈现 Child 组件.在第二个示例中,每当 MyComponent 呈现时,它都会重新创建自定义状态设置器函数,这会强制 Child 组件进行不必要的呈现.为了避免这种情况,您需要在 React.useCallback 中包装您的自定义 setter 函数以防止不必要的重新渲染,这只是另一个任意的钩子层.

because in the first example the Child component is not rerendered whenever MyComponent renders. In the second example whenever MyComponent renders, it is re-creating the custom state setter function, which forces the Child component to unnecessarily render. To avoid this, you would need to wrap your custom setter function in React.useCallback to prevent unnecessary rerenders, which is just another arbitrary layer of hooks.

这篇关于React Hooks:为什么将设置状态函数传递给子组件是不好的做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆