简体   繁体   English

React - 找到在多个父组件中使用公共组件的正确方法

[英]React - finding a proper way to use a common component amongst multiple parent components

I'm still figuring out how React works and renders its components, and have had this question for a while - supposing I have a Component D that is imported into components B & C, and both B & C are imported into component A. So the component tree would look as follows:我仍在弄清楚 React 是如何工作并渲染其组件的,并且已经有一段时间了这个问题 - 假设我有一个组件 D 被导入到组件 B 和 C 中,并且 B 和 C 都被导入到组件 A 中。所以组件树如下所示:

Component A组分 A

  • Component B B组份
    • Component D组分 D
  • Component C组件 C
    • Component D组分 D

It seems like Component D is being imported twice into Component A (albeit indirectly) via Components B & C.似乎组件 D 通过组件 B 和 C 被两次导入到组件 A 中(尽管是间接的)。 I wonder if this creates performance issues and whether I should make attempts to ensure that Component D is only included once from Component A's perspective (I guess using the Context API can resolve this?)我想知道这是否会产生性能问题,以及我是否应该尝试确保从组件 A 的角度来看仅包含一次组件 D(我想使用上下文 API 可以解决这个问题?)

We are talking about two different topics here:我们在这里讨论两个不同的主题:

  1. importing same module multiple times多次导入同一个模块
  2. using shared or individual state for multiple times imported module (you mentioned the Context API)使用共享或个人 state 多次导入模块(您提到了上下文 API)

1. importing same module multiple times 1.多次导入同一个模块

Importing the same module inside multiple other modules is totally ok.在多个其他模块中导入相同的模块是完全可以的。 Think about we are importing React in every file.想想我们在每个文件中都导入了React

Here is a nice answer regarding this topic: ES6 import duplicates这是关于这个主题的一个很好的答案: ES6 import duplicates

Additionally, below I add an example with your nested structure此外,下面我添加了一个带有嵌套结构的示例
( B and C both import D , A imports B and C ). BC都导入DA导入BC )。

Here D is passed up from both B and C to A , so that both imports can be compared inside of A , and as you can see, both D are the same,这里DBC向上传递到A ,因此可以在A内部比较两个导入,并且如您所见,两个D是相同的,
(console output: D_from_B === D_from_C: true ): (控制台 output: D_from_B === D_from_C: true ):

// -- ComponentD.jsx --

import React from 'react';
export default function ComponentD(props){
    return (<span>imported module ComponentD</span>);
};

// == ComponentC.jsx ==

import React, { useEffect } from 'react';
import ComponentD from './ComponentD';

export default function ComponentC( props ){
    useEffect(()=>{ props.passSub( ComponentD ); },[]);
    return (<div>
        <p>ComponentC</p>
        <ComponentD />
    </div>);
};

// == ComponentB.jsx ==

import React, { useEffect } from 'react';
import ComponentD from './ComponentD';

export const ComponentB = (props)=>{
    useEffect(()=>{ props.passSub( ComponentD ); });
    return (<div>
        <p>ComponentB</p>
        <ComponentD />
    </div>);
};

// == ComponentA.jsx ==

import React, { useEffect } from 'react';
import { ComponentB } from './ComponentB';
import ComponentC from './ComponentC';

let componentDfromB = null;
let componentDfromC = null;

export const ComponentA = (props)=>{

    useEffect(()=>{
        console.log('D from B === D from C:', componentDfromB === componentDfromC);      // <--- true
        console.log('Object.is(DB, DC):', Object.is(componentDfromB, componentDfromC));  // <--- true
    });

    return (<div>
        <ComponentB passSub={ function( Sub ){ componentDfromB = Sub; } } />
        <ComponentC passSub={ function( Sub ){ componentDfromC = Sub; } } />
    </div>);
};

Remark: this code shall only illustrate the point.备注:此代码仅用于说明这一点。 This approach usually does not work properly in a normal App (eg setting componentDfromB inside the callback.)这种方法在普通 App 中通常不能正常工作(例如在回调中设置componentDfromB 。)

2. using shared or individual state 2.使用共享或个人state

So, the imported modules are the same .因此,导入的模块是相同的 But the state is not .state 不是
The imported "thing" is a React.导入的“东西”是一个 React。 Component , not a React.组件,而不是 React。 Element , which is similar to the relation class vs. instance . Element ,类似于classinstance的关系。

If the React.Component D was imported, it is instantiated inside the component which has imported it, so each importing component ( B and C ) has its own instance of D , with a separate, own state.如果 React.Component D被导入,它会在导入它的组件内实例化,因此每个导入组件( BC )都有自己的D实例,以及一个单独的、自己的 state。 But that is usually exactly what you want.但这通常正是您想要的。

If you want to share the same state across different components, you would use techniques like context, redux, passing props, ... I think the details are outside the scope of this question.如果您想在不同的组件之间共享相同的 state,您将使用上下文、redux、传递道具等技术......我认为细节不在这个问题的 scope 范围内。

So what about performance...那么性能呢...

I would say performance is just no issue here, not regarding module import, and not regarding state.我想说性能在这里没有问题,与模块导入无关,也与 state 无关。

I think nobody really chooses one over the other here discussed approach for performance reasons, but for data structure or code cleanliness (of course, a bad data structure might have a bad performance, but that's not the "fault" of the React-state).我认为没有人真正出于性能原因选择这里讨论的方法,而是出于数据结构或代码清洁度的考虑(当然,糟糕的数据结构可能性能不佳,但这不是 React 状态的“错误”) .

If you are still curious about performance, I think that should be a separate, more specific question about something like "performance state vs. props".如果您仍然对性能感到好奇,我认为这应该是一个单独的、更具体的问题,例如“性能 state 与道具”。

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

相关问题 正确的React-ful方式来处理父组件中只能作用于所选子组件的函数? - Proper React-ful way to handle a function in a parent component that will only act on selected child components? 什么是从React中从同一文件导入多个组件的正确方法,而不是导入每个组件 - what is proper way to import multiple components from same file in react instead of getting each component imported 使用 Vue,在多个父组件中使用 Pagination 组件的最佳方法是什么? - Using Vue, what is the best way to use a Pagination component in multiple parent components? 测试React组件回调到父组件的好方法是什么? - What is a good way of testing React component callbacks to parent components? React 如何在同一个父组件上显示多个不同来源的组件 - React how to display multiple components of different origin on the same parent component 在 React 中从多个子组件向一个父组件发送信息 - Send information from multiple children components to one parent component in React 创建可重用组件的正确方法是什么? - What is the proper way to create reusable components react React Components - 创建它们的正确方法是什么? - React Components - What is the proper way to create them? 在反应中使用多个组件 - Use multiple components in react React - 组件导出多个组件 - React - Component export multiple components
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM