我希望能收到有关我的方法的反馈意见
背景
APPROACH
核心:
我创建了一个名为DataFetch的类,该类将从服务器获取数据,该服务器可以选择使用onReceive()和onError()方法接收Redux state options
,SignalR options
和回调。
When not configurated with Redux state options and SignalR options
:dataFetch将具有相同的axios功能。
When configurated with Redux state options
:DataFetch类将根据状态选项动态创建一个redux状态,并使用请求的结果对其进行更新。 Redux状态选项为:stateName
和reducer
。 actionTypes
将使用stateName并根据请求的成功/错误响应动态创建。
When configurated with Signal options
:dataFetch从服务器接收实时更新。如果已配置:它将更新redux状态并调用回调(onSuccess,onError)。
专业信息:
useSignalR
来轻松将SignalR与React组件一起使用。 如何使用?
我创建了一个名为useDataFetch
的钩子,以轻松地将此功能与无状态React组件一起使用。
挂钩的结果将是一个像这样的对象:{ data, error, isLoading }
。
使用钩子的语法如下:
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;