可以使用 Create React App 来初始化 Reac t应用程序,并使用 yarn 来管理依赖。
在初始化应用程序后使用:
- Ant Design的List组件来显示聊天消息
- Redux Toolkit来管理状态
- createSlice创建Redux的reducer和action
- thunk来处理异步操作
- axios库发送和接收数据
以下是代码示例:
首先,确保已经安装了Create React App和yarn。然后,在终端中执行以下命令:
npx create-react-app chat-app
cd chat-app
yarn add antd redux react-redux @reduxjs/toolkit axios
然后,将 "src/App.js" 文件的内容替换为以下代码:
import React, { useEffect } from 'react';
import { List } from 'antd';
import { useSelector, useDispatch } from 'react-redux';
import { createSlice, configureStore, createAsyncThunk, createAction } from '@reduxjs/toolkit';
import axios from 'axios';
const initialState = {
messages: [],
loading: false,
error: null,
};
const chatSlice = createSlice({
name: 'chat',
initialState,
reducers: {
addMessage: (state, action) => {
state.messages.push(action.payload);
},
setLoading: (state, action) => {
state.loading = action.payload;
},
setError: (state, action) => {
state.error = action.payload;
},
},
});
export const { addMessage, setLoading, setError } = chatSlice.actions;
export const fetchMessages = createAsyncThunk('chat/fetchMessages', async () => {
try {
const response = await axios.get('http://loriame.cn:5000/ailab/getMessages');
return response.data;
} catch (error) {
throw Error('Failed to fetch messages');
}
});
export const sendMessage = createAsyncThunk('chat/sendMessage', async (message) => {
try {
const response = await axios.post('http://loriame.cn:5000/ailab/sendMessage', message, {
headers: { 'Content-Type': 'application/json' },
});
return response.data;
} catch (error) {
throw Error('Failed to send message');
}
});
const reducer = chatSlice.reducer;
const store = configureStore({
reducer,
});
const ChatApp = () => {
const dispatch = useDispatch();
const messages = useSelector((state) => state.messages);
const loading = useSelector((state) => state.loading);
const error = useSelector((state) => state.error);
useEffect(() => {
dispatch(fetchMessages());
}, [dispatch]);
const handleSendMessage = (name, message) => {
dispatch(setLoading(true));
dispatch(setError(null));
dispatch(
sendMessage({ name, message })
).unwrap()
.then(() => {
dispatch(fetchMessages());
})
.catch((error) => {
dispatch(setError(error.message));
})
.finally(() => {
dispatch(setLoading(false));
});
};
return (
<div>
{loading && <div>Loading...</div>}
{error && <div>Error: {error}</div>}
<List
dataSource={messages}
renderItem={({ name, message }) => (
<List.Item>
<List.Item.Meta title={name} description={message} />
</List.Item>
)}
/>
</div>
);
};
const App = () => {
return (
<Provider store={store}>
<ChatApp />
</Provider>
);
};
export default App;
我们首先定义了初始状态、Redux的reducer和action,以及异步操作thunk。
在ChatApp组件中,我们使用useSelector和useDispatch来获取Redux store中的状态和派发action。在组件的useEffect钩子函数中,我们调用fetchMessages来获取聊天消息。当发送消息时,我们调用sendMessage来异步发送消息,并更新聊天消息。
最后,我们将应用程序包装在Provider组件中,以便Redux store能够在整个应用程序中共享。
|