安装依赖
npm install @reduxjs/toolkit react-redux
创建store模块
- 创建 app/store/counterSlice.js文件
"use client"
// redux需要作为客户端渲染的模块
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
},
reset: (state) => {
state.value = 0
}
}
})
export const {increment, decrement, reset} = counterSlice.actions
export default counterSlice.reducer
// 选择器函数:选择并返回特定状态的部分
export const selectCounter = (state) => state.counter.value
- 创建 app/store/store.js文件
"use client"
import { combineReducers, configureStore } from "@reduxjs/toolkit"
import counterReducer from "./counterSlice"
import { Provider } from "react-redux"
const rootReducer = combineReducers({
counter: counterReducer
})
export const store = configureStore({
reducer: rootReducer
})
export function ReduxProvider({children}) {
return (
<Provider store={store}>{children}</Provider>
)
}
使用定义好的store模块
我们可以在全局 layout 里面注册 Provider, 这样能保证我们的所有的客户端组件都能使用 Redux
全局layout.js文件
import { ReduxProvider } from "./store/store";
export default function RootLayout({ children }) {
return (
<html lang="en">
<body>
<ReduxProvider>
{children}
</ReduxProvider>
</body>
</html>
);
}
redux 在 next.js 中只能是作为客户端渲染模块使用
page.js文件
// redux在next.js中只能是作为客户端渲染模块使用
"use client"
import {increment, decrement, reset, selectCounter} from "./store/counterSlice"
import {useDispatch, useSelector} from "react-redux"
import MyCounter from "./components/demo"
export default function Home() {
const dispatch = useDispatch()
const counter = useSelector(selectCounter)
return (
<>
<h1>{counter}</h1>
<button onClick={() => dispatch(increment())}>+1</button>
<button onClick={() => dispatch(decrement())}>-1</button>
<button onClick={() => dispatch(reset())}>Reset</button>
<MyCounter />
</>
);
}
预览结果: