如何重构处理太多条件/用例的 React 组件?
How to refactor a react component that is handling too many conditions / use cases?
我想将 SOLID 原则应用于处理过多 'use cases' 的 React 组件。举个例子,假设我有一个主要职责是渲染 table 的组件,如下所示:
return (
<Table dataSource="" name={tableName} />
)
这是 table 的一个非常简单的表示。但主要的复杂点是 prop dataSource
。在这个 <Table>
组件中,我实际上有很多 logic/if-else 条件来满足组件中散落的 dataSource
标志,因为 dataSource
可以采用许多不同的形状/对象结构体。有些非常相似,可以抽象出来,而有些则非常具体(甚至可能只是一键不同)。
例如:
const tableName = `${
dataSource === 'dataSourceA'
? dataSourceName
: dataSourceName.name
}`;
这只是一个例子。想象一下 dataSource
的 name
属性 嵌套了 3 层深。然后其他 dataSource
甚至会有不同的键名(尽管我需要渲染的结果数据实际上是相同的)。不仅如此,根据 dataSource
,我可能需要调用不同的端点来执行某些功能(同样,函数的目的相同,只是端点可以不同)。因此,在同一个组件中,我将具有如下功能:
const exportTable = () => {
if(dataSource === 'dataSourceA') {
// use endpoint A
} else if (dataSource=== 'dataSourceB') {
// use endpoint B
} else {
// use endpoint C
}
}
重构这种组件并使其更易于维护的最佳方法是什么?稍后,我们可以有 10 种类型的 dataSources
,我不能在组件内做 if-else 条件来满足它们的差异。
在纯函数式风格中,您可以接受函数以及简单的 objects 道具:
if (props.name instanceof Function)
props.name = props.name(dataSource) // or some other param
通过这种方式,您可以轻松地将详细信息卸载给消费者,而不是将所有内容都放在一个地方。
那么,对于端点,为什么逻辑应该驻留在 table 组件中?保持纯粹的视觉效果,让 parent 传递细节。在 React 中,我们将视觉效果和业务逻辑保存在单独的组件中,因此您可以轻松地在应用程序的其他地方重用视图。
可以使用hooks抽象出数据是如何获取的:
const { rows, ...data } = useData(datasource)
return (
<Table row={rows} {...data} />
);
在useData
钩子中:
function useData(dataSource) {
if(dataSource === 'dataSourceA') {
// use endpoint A
} else if (dataSource=== 'dataSourceB') {
// use endpoint B
} else {
// use endpoint C
}
// ...
return data;
}
您仍然需要处理条件,但它们将与 UI 分开,这将使管理组件生命周期变得更加容易。
其次,你可以制作一个service/API层来抽象数据获取。
async function fetchFromEndpointA(args) {
const response = await httpClient
.get(`/endpointA/${args}`)
return response.body;
}
API 层将被挂钩消耗:
// react-async useAsync is a lib that helps manage async state
import { useAsync } from 'react-async';
function useData(dataSource) {
const a = useAsync({ promiseFn: fetchFromEndpointA, defer: true });
const b = useAsync({ promiseFn: fetchFromEndpointB, defer: true });
if(dataSource === 'dataSourceA') {
const { run, error, isLoading data } = a;
a.run();
return { error, isLoading, data };
}
// ...
}
你也可以从钩子中抽象出数据源解析+获取。在不知道您的数据源对象的细节的情况下,我只能推荐一个通用策略。它可能看起来像:
async function obtainData(dataSource, parseableObject) {
if(dataSource === 'dataSourceA') {
return parseableObject['name'];
} else if (dataSource === 'dataSourceB') {
const name = parseableObject[0][0].Name; // whatever the path to name is
const data = await callEndpointB(name);
return data.result;
} else {
// ...
}
}
现在任何挂钩或组件都可以调用 obtainData
而无需知道条件。 hook/component 只需要跟踪异步状态。
例如,在一个钩子中:
function useData(dataSource, parseableObject) {
return useAsync({ promiseFn: () => obtainData(dataSource, parseableObject) });
}
或者,只需在组件中调用它并完全放弃自定义挂钩:
const { rows, ...data } = useAsync({ promiseFn: () => obtainData(dataSource, parseableObject) });
return (
<Table row={rows} {...data} />
);
在做出决定之前,您可能需要探索很多可能性。
最后,关于重构的一些常见建议:
在抽象或重构之前,首先通过可靠的、人类可读的测试使所有具体的高级行为正确无误。快速而肮脏的代码很好。不要依赖于测试实现细节或内部抽象。然后,如果以后出现清晰的模式,您可以使用现有测试来指导您进行重构。
考虑成本。有一句程序员的谚语类似于“没有抽象胜过错误的抽象”。如果您决定将代码重新组织到单独的层中,则需要主动了解它对可维护性等方面的影响。查看 WET Codebase。而不是我在这里总结,你最好 watch/read 它并收集你自己的见解。
我喜欢。它很整洁,并且很好地抽象了东西。
作为替代方案,我过去已经完成了您在 useEffect
函数中描述的操作。
注意:也许 useMemo
也有理由,但我会专注于 useEffect
。
import { parseTableData, TableData } from '../util/for/table/data';
interface TableProps {
data: TableData; // Typing this would be super useful
name: string;
}
const Table: React.FC<TableProps> = ({ name, data }) => {
const [tableData, setTableData] = useState<TableData>(); // undefined on init
useEffect(
() => parseTableData(setTableData, data),
[data, setTableData]
);
if (!tableData) {
return <p>Parsing... please wait.</P>
}
// Here, you can use `tableData` knowing that it has been formatted properly
return ...
}
然后,您可以将解析器逻辑抽象到一个单独的文件中:
interface TableData {
...
}
export const parseTableData = (
setTableData: React.Dispatch<React.SetStateAction<TableData>>,
data?: TableData,
) => {
// Do whatever parsing / massaging you want to with the data here,
// and build the required response for the state variable.
const response: TableData = {
...
}
setTableData(response);
}
我想将 SOLID 原则应用于处理过多 'use cases' 的 React 组件。举个例子,假设我有一个主要职责是渲染 table 的组件,如下所示:
return (
<Table dataSource="" name={tableName} />
)
这是 table 的一个非常简单的表示。但主要的复杂点是 prop dataSource
。在这个 <Table>
组件中,我实际上有很多 logic/if-else 条件来满足组件中散落的 dataSource
标志,因为 dataSource
可以采用许多不同的形状/对象结构体。有些非常相似,可以抽象出来,而有些则非常具体(甚至可能只是一键不同)。
例如:
const tableName = `${
dataSource === 'dataSourceA'
? dataSourceName
: dataSourceName.name
}`;
这只是一个例子。想象一下 dataSource
的 name
属性 嵌套了 3 层深。然后其他 dataSource
甚至会有不同的键名(尽管我需要渲染的结果数据实际上是相同的)。不仅如此,根据 dataSource
,我可能需要调用不同的端点来执行某些功能(同样,函数的目的相同,只是端点可以不同)。因此,在同一个组件中,我将具有如下功能:
const exportTable = () => {
if(dataSource === 'dataSourceA') {
// use endpoint A
} else if (dataSource=== 'dataSourceB') {
// use endpoint B
} else {
// use endpoint C
}
}
重构这种组件并使其更易于维护的最佳方法是什么?稍后,我们可以有 10 种类型的 dataSources
,我不能在组件内做 if-else 条件来满足它们的差异。
在纯函数式风格中,您可以接受函数以及简单的 objects 道具:
if (props.name instanceof Function)
props.name = props.name(dataSource) // or some other param
通过这种方式,您可以轻松地将详细信息卸载给消费者,而不是将所有内容都放在一个地方。
那么,对于端点,为什么逻辑应该驻留在 table 组件中?保持纯粹的视觉效果,让 parent 传递细节。在 React 中,我们将视觉效果和业务逻辑保存在单独的组件中,因此您可以轻松地在应用程序的其他地方重用视图。
可以使用hooks抽象出数据是如何获取的:
const { rows, ...data } = useData(datasource)
return (
<Table row={rows} {...data} />
);
在useData
钩子中:
function useData(dataSource) {
if(dataSource === 'dataSourceA') {
// use endpoint A
} else if (dataSource=== 'dataSourceB') {
// use endpoint B
} else {
// use endpoint C
}
// ...
return data;
}
您仍然需要处理条件,但它们将与 UI 分开,这将使管理组件生命周期变得更加容易。
其次,你可以制作一个service/API层来抽象数据获取。
async function fetchFromEndpointA(args) {
const response = await httpClient
.get(`/endpointA/${args}`)
return response.body;
}
API 层将被挂钩消耗:
// react-async useAsync is a lib that helps manage async state
import { useAsync } from 'react-async';
function useData(dataSource) {
const a = useAsync({ promiseFn: fetchFromEndpointA, defer: true });
const b = useAsync({ promiseFn: fetchFromEndpointB, defer: true });
if(dataSource === 'dataSourceA') {
const { run, error, isLoading data } = a;
a.run();
return { error, isLoading, data };
}
// ...
}
你也可以从钩子中抽象出数据源解析+获取。在不知道您的数据源对象的细节的情况下,我只能推荐一个通用策略。它可能看起来像:
async function obtainData(dataSource, parseableObject) {
if(dataSource === 'dataSourceA') {
return parseableObject['name'];
} else if (dataSource === 'dataSourceB') {
const name = parseableObject[0][0].Name; // whatever the path to name is
const data = await callEndpointB(name);
return data.result;
} else {
// ...
}
}
现在任何挂钩或组件都可以调用 obtainData
而无需知道条件。 hook/component 只需要跟踪异步状态。
例如,在一个钩子中:
function useData(dataSource, parseableObject) {
return useAsync({ promiseFn: () => obtainData(dataSource, parseableObject) });
}
或者,只需在组件中调用它并完全放弃自定义挂钩:
const { rows, ...data } = useAsync({ promiseFn: () => obtainData(dataSource, parseableObject) });
return (
<Table row={rows} {...data} />
);
在做出决定之前,您可能需要探索很多可能性。
最后,关于重构的一些常见建议:
在抽象或重构之前,首先通过可靠的、人类可读的测试使所有具体的高级行为正确无误。快速而肮脏的代码很好。不要依赖于测试实现细节或内部抽象。然后,如果以后出现清晰的模式,您可以使用现有测试来指导您进行重构。
考虑成本。有一句程序员的谚语类似于“没有抽象胜过错误的抽象”。如果您决定将代码重新组织到单独的层中,则需要主动了解它对可维护性等方面的影响。查看 WET Codebase。而不是我在这里总结,你最好 watch/read 它并收集你自己的见解。
我喜欢
作为替代方案,我过去已经完成了您在 useEffect
函数中描述的操作。
注意:也许 useMemo
也有理由,但我会专注于 useEffect
。
import { parseTableData, TableData } from '../util/for/table/data';
interface TableProps {
data: TableData; // Typing this would be super useful
name: string;
}
const Table: React.FC<TableProps> = ({ name, data }) => {
const [tableData, setTableData] = useState<TableData>(); // undefined on init
useEffect(
() => parseTableData(setTableData, data),
[data, setTableData]
);
if (!tableData) {
return <p>Parsing... please wait.</P>
}
// Here, you can use `tableData` knowing that it has been formatted properly
return ...
}
然后,您可以将解析器逻辑抽象到一个单独的文件中:
interface TableData {
...
}
export const parseTableData = (
setTableData: React.Dispatch<React.SetStateAction<TableData>>,
data?: TableData,
) => {
// Do whatever parsing / massaging you want to with the data here,
// and build the required response for the state variable.
const response: TableData = {
...
}
setTableData(response);
}