使用redux结合Redux Toolkit写一个计数器并调用它
时间: 2024-05-09 08:21:51 浏览: 117
好的,我知道该怎么回答了。以下是使用redux结合Redux Toolkit写一个计数器的代码示例:
首先需要安装redux、react-redux和@reduxjs/toolkit依赖:
```
npm install --save redux react-redux @reduxjs/toolkit
```
接着,创建一个redux store,并在里面定义一个计数器:
```javascript
import { createSlice, configureStore } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0,
},
reducers: {
increment: (state) => {
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
},
})
const store = configureStore({
reducer: counterSlice.reducer,
})
export const { increment, decrement } = counterSlice.actions
export default store
```
然后,在React组件中使用相应的计数器:
```javascript
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { increment, decrement } from './store'
function Counter() {
const count = useSelector((state) => state.value)
const dispatch = useDispatch()
return (
<div>
<h1>{count}</h1>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
</div>
)
}
export default Counter
```
这样,一个使用redux结合Redux Toolkit实现的计数器就完成了。希望这个示例可以帮到你。
阅读全文