首页 > 解决方案 > 上下文不适用时的下一个最佳选择

问题描述

我需要两个 React 组件来交换数据,但我不能使用 React Context。这是我无法控制的,我将两个单独的第三方“小部件”带到同一网页的不同区域。

我有什么选择?现在,我所做的是创建一个独立的对象,我在两个组件中都导入了该对象。对此有什么顾虑吗,有没有更好的方法?

共享对象:PP_Properties.js

function PP_PropertiesFactory()  {
    let properties = {Property1: null, Property2: null, Property3: null};

    const updateProperties = ({targetProperty, newValue}) => properties[targetProperty] = newValue;

    return {...properties, updateProperties};
}

export const PP_Properties = PP_PropertiesFactory();

小部件 1 组件

import * as React from 'react';
import * as ReactDOM from 'react-dom';

import {PP_Properties} from './PP_Properties';

export const Widget1Component = (props) => {
  // Use PP_Properties in this element
  // Update PP_Properties using the updateProperties() method
};

小部件 2 组件

import * as React from 'react';
import * as ReactDom from 'react-dom';

import {PP_Properties} from './PP_Properties';

export class Widget2ComponentBuilder {
  // Consume PP_Properties in this element
  // Update PP_Properties using updateProperties()
}

export function Widget2Component() {
  return new Widget2ComponentBuilder();
};

标签: reactjsreact-context

解决方案


在做了一些阅读之后,似乎我要求的是一个做全局状态管理的库,比如 Redux。

一个完整的库可能对我的简单需求来说有点过头了,所以我正在寻找更轻量级的选项。到目前为止我听到的名字是 mobx、ReactN、React Entities 和 React Capsule。

一个更简单的方法是保留我对两个组件导入和操作的对象的最初想法。正如@drew-reese 所说,起初它看起来像是一种反模式,但实际上这些状态管理库就是这样工作的。

这是一个例子:

https://dev.to/muhammadawaisshaikh/the-simplest-way-to-share-data-between-two-unrelated-components-in-react-1md0


推荐阅读