【发布时间】:2018-11-03 19:36:24
【问题描述】:
我正在创建一个实现 SignalR 的 react 应用程序,到目前为止,我有我的连接和组件中我需要它们的所有侦听器。问题是我在 Redux 中有动作创建者,它们只是发出请求并获取响应,以便调用我的服务器并将数据发送到所有其他客户端。一旦服务器向所有客户端发出事件,我的一个监听器就会获取数据并调用一个动作创建者,该创建者只是调度一个动作来刷新我的 redux 状态。
我觉得我没有以正确的方式使用动作创建器,因为我有一个动作创建器,它只是发出请求并获得响应以返回它,它并没有改变状态。
如果在商店中有套接字连接,我只需调用一个动作创建者,发出或监听套接字事件的逻辑将在其他地方。
这是我的组件,
// --- component.js ---
state = {
connection: null,
};
async componentDidMount() {
// handles any network exception and show the error message
try {
await this.setupConnection();
} catch (error) {
this.showNetworkError(`Whoops, there was an error with your network connection. Please reload the page`);
}
setupConnection = () => {
let { connection } = this.state;
this.setState({
connection: (connection = new HubConnectionBuilder().withUrl(HUB_URL).build()),
});
/**
* LISTENERS that are called from the server via websockets
*/
connection.on('InsertTodo', data => {
// action creator
this.props.add(data);
});
connection.on('UpdateTodo', data => {
// action creator
this.props.update(data);
});
}
createTodo = async todo => {
const { connection} = this.state;
// action creator
const createdTodo = await this.props.createTodo(todo);
if (createdTodo) {
// the below sentence calls the server to emit/send the todo item to all other clients
// and the listener in the setupConnection function is executed
connection.invoke('EmitTodoCreate', createdTodo);
} else {
// there was a problem creating the todo
}
};
这是动作创建者
// --- actionCreators.js ----
// ------------------------
export const add = todo => {
return async (dispatch) => {
dispatch({
type: ADD_TODO,
payload: todo,
});
};
};
export const createTodo = todo => {
return async (dispatch) => {
dispatch({
type: START_REQUEST,
});
const response = await postTodo(todo);
const result = await response.json();
if (response.ok) {
dispatch({
type: SUCCESS_REQUEST,
});
// returns the todo item created in order to be sent to the server via websockets
return result;
}
dispatch({
type: FAILURE_REQUEST,
error: result.error,
});
return null;
};
};
【问题讨论】: