[英]Is it better to use React context instead of passing the same object to dozens of components?
I'm adding user comments in my website and I need to pass user object to each user comment.我在我的网站中添加用户评论,我需要将用户对象传递给每个用户评论。 I have a React component called
UserReplyForm
which handles submit of new comment.我有一个名为
UserReplyForm
的 React 组件,它处理新评论的提交。 A user can reply to each comment so visually there's a component to display a comment and a form below each comment to reply.用户可以回复每条评论,因此在视觉上有一个组件来显示评论和每个评论下方的表单以供回复。
The user object is stored in a React context.用户对象存储在 React 上下文中。 Because I will have dozens of replies and potentially dozens of replies to replies I'm wondering if it's better in terms of memory optimization to get the user object via React context because if I pass it as props, the user object will be copied as many times as there're replies.
因为我将有几十个回复,并且可能有几十个回复我想知道通过 React 上下文获取用户对象在内存优化方面是否更好,因为如果我将它作为道具传递,用户对象将被复制尽可能多有回复的时候。 When I say copied I mean that function parameters are copied by value in Javascript.
当我说复制时,我的意思是在 Javascript 中按值复制函数参数。 On the other hand getting the user object from the user context I think I will just get the reference to the object.
另一方面,从用户上下文中获取用户对象,我想我只会获取对对象的引用。
EDIT: come to think of it, using context doesn't really help because if I use context I will save the context result in a local variable which also uses memory.编辑:想想看,使用上下文并没有真正的帮助,因为如果我使用上下文,我会将上下文结果保存在一个也使用内存的局部变量中。 So props and context result in same memory usage.
所以道具和上下文导致相同的内存使用。
当然,这就是上下文的目的。
function's passed by reference and .its parameters are also passed by reference (if it's object,array,..) and was linked to the function pointer.When function's called, it will get value of its parameters through the linked pointer.函数通过引用传递,.它的参数也是通过引用传递(如果是对象,数组,..)并链接到函数指针。当函数被调用时,它将通过链接指针获取其参数的值。 It's just my thinking, feel free to correct.
这只是我的想法,欢迎指正。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.