使用redux结合Redux Toolkit写一个计数器并且在App.js中使用它
时间: 2024-05-05 07:20:27 浏览: 102
手把手教你在小程序里使用 Redux
好的,让我来回答你的问题。
首先,需要在项目中安装 redux 和 @reduxjs/toolkit:
```
npm install redux @reduxjs/toolkit
```
接着,创建一个 reducer 文件(比如 counterSlice.js),定义一个初始状态和一个 reducer 函数:
```
import { createSlice } from '@reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: { value: 0 },
reducers: {
increment: (state) => {
state.value++
},
decrement: (state) => {
state.value--
},
},
})
export const { increment, decrement } = counterSlice.actions
export default counterSlice.reducer
```
在 App.js 中使用这个计数器:
```
import React from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { increment, decrement } from './counterSlice'
function App() {
const count = useSelector((state) => state.counter.value)
const dispatch = useDispatch()
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={() => dispatch(increment())}>+</button>
<button onClick={() => dispatch(decrement())}>-</button>
</div>
)
}
export default App
```
最后,需要在应用程序的顶层使用 Redux 的 Provider 组件,以便将 store 注入到组件树中:
```
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import { configureStore } from '@reduxjs/toolkit'
import counterReducer from './counterSlice'
import App from './App'
const store = configureStore({
reducer: {
counter: counterReducer,
},
})
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
```
这样就完成了一个使用 Redux Toolkit 开发的计数器应用。希望我的回答对你有帮助!
阅读全文