必须接入redux以实现可预测状态管理与调试能力,使用@reduxjs/toolkit初始化store、定义slice并配合react-redux的provider和hook完成集成。
☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 多模态理解力帮你轻松跨越从0到1的创作门槛☜☜☜

在Cursor编辑器中新建React项目后,要让状态管理具备可预测性和调试能力,必须接入Redux。Cursor本身不改变React生态的集成逻辑,但它的AI补全和文件导航能加速配置过程,前提是路径和API调用完全符合当前主流工具链。
创建项目并安装核心依赖
打开Cursor终端(Cmd/Ctrl+J),执行以下命令初始化项目并安装Redux相关库:
npx create-react-app my-app --template typescript → cd my-app → npm install react-redux @reduxjs/toolkit
注意:不要使用旧版redux或单独安装redux-thunk——【@reduxjs/toolkit已内置thunk中间件和DevTools支持】,手动引入反而会引发版本冲突。
构建标准Store结构
在src目录下新建store文件夹,创建index.ts:
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../features/counter/counterSlice';
export const store = configureStore({
reducer: {
counter: counterReducer,
}
});
export type RootState = ReturnType
export type AppDispatch = typeof store.dispatch;
这一步必须用configureStore而非createStore——【旧版createStore不兼容RTK的自动DevTools注入和immer式不可变更新】,否则后续调试面板将无法捕获action。
将Store注入React应用根节点
修改src/main.tsx(或index.tsx):
import React from 'react';
import ReactDOM from 'react-dom/client';
import { Provider } from 'react-redux';
import { store } from './store';
import App from './App';
ReactDOM.createRoot(document.getElementById('root')!).render(
);
确保Provider包裹整个
定义Slice并使用Hook读写状态
在src/features/counter目录下创建counterSlice.ts:
import { createSlice } from '@reduxjs/toolkit';
export const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: state => { state.value += 1 },
decrement: state => { state.value -= 1 },
incrementByAmount: (state, action) => { state.value += action.payload }
}
});
export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default counterSlice.reducer;
在App.tsx中使用:
import { useSelector, useDispatch } from 'react-redux';
import { increment, decrement, incrementByAmount } from './features/counter/counterSlice';
function App() {
const count = useSelector((state: RootState) => state.counter.value);
const dispatch = useDispatch();
return (
{count}
);
}
export default App;
useSelector必须传入类型断言RootState,否则TS会报错“cannot find name RootState”;dispatch调用时无需手动解构action creator,RTK已自动绑定payload类型。











