安装必要依赖
redux
:Redux 核心库,用于状态管理。通过 npm 安装:npm install redux
。
react-redux
:使 React 应用能够与 Redux 集成。安装命令:npm install react-redux
。
基本步骤
- 创建 Redux store:
- 在项目合适位置(如
src/store.js
),导入 createStore
等必要函数。
- 创建 reducer 来定义状态如何响应 actions 变化。
- 使用
createStore
创建 store 实例,例如:
import { createStore } from'redux';
// 创建 reducer
const reducer = (state = initialState, action) => {
switch (action.type) {
// 处理不同 action 逻辑
default:
return state;
}
};
const store = createStore(reducer);
export default store;
- 在 Qwik 应用中提供 store:
- 在应用入口(如
main.tsx
),导入 Provider
组件(来自 react-redux
)和创建好的 store
。
- 使用
Provider
包裹应用顶层组件,将 store
作为 prop 传递,示例:
import { Provider } from'react-redux';
import store from './store';
import { component$, render$ } from '@builder.io/qwik';
import App from './App';
const root = component$(() => {
return (
<Provider store={store}>
<App />
</Provider>
);
});
render$(root, document.getElementById('root'));
- 在组件中使用 Redux 状态:
- 在需要使用 Redux 状态的组件中,导入
useSelector
和 useDispatch
钩子(来自 react-redux
)。
- 使用
useSelector
获取状态,例如:
import { useSelector } from'react-redux';
const MyComponent = () => {
const myState = useSelector(state => state.someSlice);
return (
<div>
{myState}
</div>
);
};
export default MyComponent;
- 使用 `useDispatch` 分发 actions 来更新状态,例如:
import { useDispatch } from'react-redux';
const MyComponent = () => {
const dispatch = useDispatch();
const handleClick = () => {
dispatch({ type: 'SOME_ACTION' });
};
return (
<button onClick={handleClick}>Click me</button>
);
};
export default MyComponent;