[英]React and Redux: Are there any performance issues/possible side effects with passing a parent component as a prop to its children
I'm reviewing some code in a React-Redux codebase, and there are quite a few cases where a parent smart component is being passed as a prop to a child component: 我正在查看React-Redux代码库中的一些代码,在很多情况下,将父智能组件作为道具传递给子组件:
import React from 'react';
import Child from '../components/Child';
export default class Parent extends React.Component {
constructor(props) {
super(props);
}
//...
render() {
return <Child parent={this}/>;
}
}
At initial glance, it appears that the intention here is to expose the props/state/methods of the parent to the child component. 乍看之下,这里的意图似乎是将父级的道具/状态/方法暴露给子级组件。 This sort of goes against many of the design patterns I've used in the past with React, but I'm not sure if it's something that is worth bringing up in a code review (it's already deployed to QA).
这种情况与我过去在React中使用的许多设计模式背道而驰,但是我不确定是否值得在代码审查中提出(已经部署到QA中)。 It technically works (the child is able to call this.props.parent[method], etc) and significantly reduces the lines of code otherwise required if you pass individual handlers/slices of props/(local)state to the child.
从技术上讲,它可以正常工作(孩子可以调用this.props.parent [method]等),并且如果您将单独的处理程序/ slice片段/(本地)状态传递给孩子,则可以大大减少否则需要的代码行。 I know there are downsides (in one case, the parent property shared the same name as a reducer, so in the child component, it is unclear if this.props['reducerName'] is referring to a React Component or a mapped slice of state), but I can't be sure that the downsides are anything more than surface level.
我知道有缺点(在一种情况下,父属性与减速器共享相同的名称,因此在子组件中,尚不清楚this.props ['reducerName']是指React组件还是映射的切片。状态),但我无法确定缺点是否只是表面水平。
Does something like this run the risk of unnecessary rerenders/diff checks in the child component? 这样的事情冒着在子组件中进行不必要的重新渲染/差异检查的风险吗? Does React ever need to recursively serialize components, and thus incur a lot of overhead because of circular references?
React是否需要递归地序列化组件,从而由于循环引用而导致大量的开销? Anything I can point out besides I don't think it looks right?
除了我认为不正确之外,我还能指出什么吗?
There are a few things I can think of why this might not be a good Idea: 我可以想到几件事,为什么这可能不是一个好主意:
One case where it can be very bad idea is when the child component changes something on the date object: eg : 一种可能非常不好的主意是子组件更改日期对象上的某些内容:例如:
render() { return ( <React.Fragment> <ChildOne parent={this}/>; <ChildTwo parent={this}/>; </React.Fragment> ) }
Now the ChildOne
component can do something like : 现在,
ChildOne
组件可以执行以下操作:
this.props.parent.clickHandler = this.anotherHandler
This will break ChildTwo
functionality. 这将破坏
ChildTwo
功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.