[英]Easy setup react redux with next.js (React)
我已經看到使用 redux 的 next.js 示例。 但是有沒有簡單的方法來設置 redux 和 next.js? 我想設置 redux 我過去是如何使用 react.js 設置的
我建議使用redux 工具包,因為它減少了 redux 中的樣板代碼......
使用createSlice ,您可以同時創建 Action 和 Reducer。 如果將 API 調用發送到后端並為待處理、已完成和已拒絕的 API 調用執行適當的 state 突變,那么 createAsyncThunk是最好的!
根據我的個人經驗,如果您只是為了初步學習而問這個問題,那么您作為答案附加的第一個設置就足夠了,但對於真正的應用程序來說,go 和 Redux 工具包絕對應該。 您可以查看此沙盒示例
假設你對 Redux 有 React 方面的知識。
首先,安裝這些包
$ npm install next-redux-wrapper react-redux redux redux-thunk --save
$ npm install redux-devtools-extension --save-dev
覆蓋或創建默認 App,創建文件./pages/_app.js
如下圖:
import withRedux from 'next-redux-wrapper'
import { Provider } from 'react-redux'
import { withRouter } from 'next/router'
import App from 'next/app'
import createStore from 'store/createStore'
class MyApp extends App {
render () {
const { Component, pageProps, router, store } = this.props
return (
<Provider store={store}>
<Component router={router} {...pageProps} />
</Provider>
)
}
}
export default withRedux(createStore)(
withRouter(MyApp)
)
在您的頁面/組件中,您可以像往常一樣使用 Redux。
這是我最簡單的方法,你可以照着做。 https://github.com/imimran/next-redux-example
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.