reactjs - 上下文不适用时的下一个最佳选择
问题描述
我需要两个 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();
};
解决方案
在做了一些阅读之后,似乎我要求的是一个做全局状态管理的库,比如 Redux。
一个完整的库可能对我的简单需求来说有点过头了,所以我正在寻找更轻量级的选项。到目前为止我听到的名字是 mobx、ReactN、React Entities 和 React Capsule。
一个更简单的方法是保留我对两个组件导入和操作的对象的最初想法。正如@drew-reese 所说,起初它看起来像是一种反模式,但实际上这些状态管理库就是这样工作的。
这是一个例子:
推荐阅读
- flutter - 带有提供程序包 UI 的颤振不会在详细信息页面上更新
- c# - 围绕物体旋转相机,轻松改变位置
- javascript - iOS Safari 13.5 flickering on fixed element with long content
- node.js - Unable to upload file to S3 due to write EPIPE Networking Error
- html - Make divs on the top of the other div
- c# - C# - How to insert bulk data in Excel via Microsoft Office Interop Excel
- php - apache/php/oci 自动用问号替换 unicode 字符 - 如何?
- javascript - vue-cli eslint 没有捕获错误
- php - 将 guzzle 响应数据推送到数组并传递给 laravel 中的查看
- steam - 如何获取给定 Steam 应用程序的所有所有者?