用react+ts和Redux-Toolkit写一个简单的例子
时间: 2024-10-08 13:16:37 浏览: 36
在React应用中结合TypeScript (TS) 和 Redux Toolkit编写一个简单例子,首先你需要安装必要的依赖:
```sh
npm install react redux react-redux redux-toolkit @reduxjs/toolkit
```
然后创建基本文件结构,如`store.ts`用于设置Redux store,`actions.ts`用于定义action creators,`reducer.ts`负责处理state的变化,`components`目录下有`App.js`作为入口组件。
**store.ts**
```typescript
// store.ts
import { configureStore } from '@reduxjs/toolkit';
import rootReducer from './reducers';
export default configureStore({
reducer: rootReducer,
});
```
**actions.ts**
```typescript
// actions.ts
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios'; // 引入axios进行API请求
const fetchData = createAsyncThunk('fetch/data', async () => {
const response = await axios.get('https://api.example.com/data');
return response.data;
});
export const fetchDataAction = () => dispatch => dispatch(fetchData());
```
**reducer.ts**
```typescript
// reducer.ts
import { createReducer, on } from '@reduxjs/toolkit';
import { fetchDataFulfilled } from './actions';
export const initialState = {
data: null,
loading: false,
error: null,
};
export const rootReducer = createReducer(
initialState,
on(fetchDataFulfilled, (state, action) => ({
...state,
data: action.payload,
loading: false,
})),
);
export default rootReducer;
```
**App.js**
```jsx
// App.js
import React, { useEffect, useSelector } from 'react';
import { useDispatch, useSelector as select } from 'react-redux';
import { fetchDataAction } from './actions';
function App() {
const dispatch = useDispatch();
const data = useSelector(state => state.fetch.data);
const loading = useSelector(state => state.fetch.loading);
const error = useSelector(state => state.fetch.error);
useEffect(() => {
dispatch(fetchDataAction());
}, [dispatch]);
if (loading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>Data:</h1>
{data && JSON.stringify(data)}
</div>
);
}
export default App;
```
在这个例子中,我们创建了一个简单的Redux store,并通过`useDispatch`从store获取action creator `fetchDataAction`。当组件挂载时,我们会触发数据加载操作,然后在reducer中处理数据的异步变化。`App.js`展示了如何展示状态变化后的结果。
阅读全文