Javascript 使用动态Redux状态和信号器反应无状态功能组件
我希望得到有关我的方法的反馈: 背景Javascript 使用动态Redux状态和信号器反应无状态功能组件,javascript,reactjs,redux,react-redux,signalr,Javascript,Reactjs,Redux,React Redux,Signalr,我希望得到有关我的方法的反馈: 背景 应用程序需要有从服务器获取数据的组件 这些组件将收到来自服务器的频繁更新 将有多个组件使用相同的数据模型 将有不同类型的数据模型 只需更改数据模型名称,就可以轻松添加新组件 应用程序可能是可配置的 方法 核心: 我创建了一个名为DataFetch的类,该类将从服务器获取数据,服务器可以选择接收Redux state options、signar options以及使用onReceive()和onError()方法的回调 未配置Redux状态选项和信号器
- 应用程序需要有从服务器获取数据的组件李>
- 这些组件将收到来自服务器的频繁更新李>
- 将有多个组件使用相同的数据模型
- 将有不同类型的数据模型
- 只需更改数据模型名称,就可以轻松添加新组件
- 应用程序可能是可配置的
Redux state options
、signar options
以及使用onReceive()和onError()方法的回调
:数据提取将具有相同的axios功能未配置Redux状态选项和信号器选项时
:DataFetch类将根据状态选项动态创建Redux状态,并使用请求的结果对其进行更新。Redux状态选项是:配置Redux状态选项时
和stateName
。reducer
将使用stateName和请求的成功/错误响应动态创建actionTypes
:数据提取从服务器接收实时更新。如果配置:它将更新redux状态并调用回调(onSuccess、onError)配置信号选项时
- 我正在使用从服务器获取数据
- 此状态已使用官方redux方法动态创建:
- 我正在使用将实时功能添加到应用程序中
- 我创建了一个钩子
,以方便地将signar与React组件一起使用李>usesigner
- 所有这些都被分为各自的类,函数易于测试
useDataFetch
的钩子,以便在“无状态组件”中轻松使用此功能
钩子的结果将是这样一个对象:{data,error,isload}
使用钩子的语法如下所示:
import React from 'react';
import { useSignalRContext } from './core/signalR';
import {
useDataFetch,
SignalRHubOptions,
ReduxStoreOptions
} from './core/dataFetch';
const ExampleComponent = props => {
const { dataModelId } = props;
const { someHubConnection } = useSignalRContext();
const signalRHubOptions = useMemo(
() =>
new SignalRHubOptions({
hubConnection: someHubConnection,
// Multiple components can be created for the same hubConnection.
// Therefore, we need to add a dataChangeMethodName by the component instance,
// otherwise, all instances of that component will receive the same message.
dataChangeMethodName: `DataChanged-${dataModelId}`
}),
[someHubConnection, dataModelId]
);
const reduxStoreOptions = useMemo(
() =>
new ReduxStoreOptions({
// Use diferrent stateName for different conponents.
stateName: `${dataModelId}_state`,
initialState: []
}),
[dataModelId]
);
// Receive data when:
// - perform the request with success;
// - signalR send a message;
// - redux state receive a update with the actionType SUCCESS;
// Receive error when:
// - perform the request with error;
// - redux state receive a update with the actionType FAILURE.
const { data, error, isLoading } = useDataFetch({
url: '/endpoint/${dataModelId}',
data: {
param1: 'value1'
},
signalRHubOptions: signalRHubOptions,
reduxStoreOptions: reduxStoreOptions
});
return {
/* render the component with the data or error or isLoading state */
};
};
export default ExampleComponent;