在Storybook中使用redux-toolkit可以通过以下步骤:
npm install redux react-redux
npm install @reduxjs/toolkit
import { createSlice } from '@reduxjs/toolkit';
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value += 1;
},
decrement: (state) => {
state.value -= 1;
},
},
});
export const { increment, decrement } = counterSlice.actions;
export default counterSlice.reducer;
import React from 'react';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import counterReducer from '../path/to/counterSlice';
const store = configureStore({
reducer: {
counter: counterReducer,
},
});
export const decorators = [
(Story) => (
<Provider store={store}>
<Story />
</Provider>
),
];
import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { increment, decrement } from '../path/to/counterSlice';
const Counter = () => {
const count = useSelector((state) => state.counter.value);
const dispatch = useDispatch();
return (
<div>
<button onClick={() => dispatch(increment())}>Increment</button>
<span>{count}</span>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
};
export default {
title: 'Components/Counter',
component: Counter,
};
这样,你就可以在Storybook中使用redux-toolkit了。当你运行Storybook时,你将能够看到Counter组件并且可以通过按钮进行增加或减少操作。注意,上面的示例仅包含了redux-toolkit的基本用法,你可以根据自己的项目需求进行扩展和修改。
腾讯云相关产品推荐:在使用Storybook时,腾讯云的云服务器ECS可以提供稳定的计算资源,可满足Storybook的部署和运行需求。你可以了解更多关于腾讯云云服务器ECS的信息和产品介绍,可以访问以下链接地址:
领取专属 10元无门槛券
手把手带您无忧上云