首先我們會用到哪些框架和工具呢?reactui框架redux狀態管理工具,與react沒有任何關係,其他ui框架也可以使用reduxreact-reduxreact外掛程式,作用:方便在react專案中使用reduxreact-thunk中介軟體,作用:支援非同步action
準備工作第1步:提供預設值,既然用redux來管理資料,那麼資料就一定要有預設值,所以我們將state的預設值統一放置在state.js檔案:|--src
|-- store redux目錄
|-- actions.js
|-- index.js
|-- reducers.js
|-- state.js
|-- components 元件目錄
|-- test.jsx
第2步:建立reducer,它就是將來真正要用到的資料,我們將其統一放置在reducers.js檔案// state.js
// 宣告預設值
// 這裡我們列舉兩個示例
// 同步資料:pagetitle
// 非同步資料:infolist(將來用非同步介面獲取)
export default
第3步:建立action,現在我們已經建立了reducer,但是還沒有對應的action來操作它們,所以接下來就來編寫action// reducers.js
// 工具函式,用於組織多個reducer,並返回reducer集合
import from 'redux'
// 預設值
import defaultstate from './state.js'
// 乙個reducer就是乙個函式
function pagetitle (state = defaultstate.pagetitle, action)
}function infolist (state = defaultstate.infolist, action)
}// 匯出所有reducer
export default combinereducers()//面向1-3年前端人員
//幫助突破技術瓶頸,提公升思維能力
最後一步:建立store例項// actions.js
// action也是函式
export function setpagetitle (data) )
}}export function setinfolist (data)
}).then(res => ).then(data => = data
if (code === 0) )}})
}}
至此,我們已經完成了所有使用redux的準備工作,接下來就在react元件中使用redux// index.js
// createstore: 用於建立store例項
// 中介軟體,作用:如果不使用該中介軟體,當我們dispatch乙個action時,需要給dispatch函式傳入action物件;但如果我們使用了這個中介軟體,那麼就可以傳入乙個函式,這個函式接收兩個引數:dispatch和getstate。這個dispatch可以在將來的非同步請求完成後使用,對於非同步action很有用
import thunk from 'redux-thunk'
// 引入reducer
import reducers from './reducers.js'
// 建立store例項
let store = createstore(
reducers,
)export default store
import react from 'react'
import reactdom from 'react-dom'
// 引入元件
import testcomponent from './components/test.jsx'
// provider是react-redux兩個核心工具之一,作用:將store傳遞到每個專案中的元件中
// 第二個工具是connect,稍後會作介紹
import from 'react-redux'
// 引入建立好的store例項
import store from '@/store/index.js'
// 渲染dom
reactdom.render (
(
),document.getelementbyid('root'))
最後是我們的元件:test.jsx
// test.jsx
import react, from 'react'
// connect方法的作用:將額外的props傳遞給元件,並返回新的元件,元件在該過程中不會受到影響
import from 'react-redux'
// 引入action
import from '../store/actions.js'
class test extends component
componentdidmount () = this.props
// 觸發setpagetitle action
setpagetitle('新的標題')
// 觸發setinfolist action
setinfolist()
} render () = this.props
// 使用store
return ()}}
// mapstatetoprops:將state對映到元件的props中
const mapstatetoprops = (state) =>
}// mapdispatchtoprops:將dispatch對映到元件的props中
const mapdispatchtoprops = (dispatch, ownprops) => )
)*/},
setinfolist (data)
}}export default connect(mapstatetoprops, mapdispatchtoprops)(test)
優雅的在React專案中使用Redux
首先我們會用到哪些框架和工具呢?ui框架 狀態管理工具,與react沒有任何關係,其他ui框架也可以使用redux react外掛程式,作用 方便在react專案中使用redux 中介軟體,作用 支援非同步action tips 與redux無關的目錄已省略 src store redux目錄 ac...
優雅的在React專案中使用Redux
或許你當前的專案還沒有到應用redux的程度,但提前了解一下也沒有壞處首先我們會用到哪些框架和工具呢?react ui框架 redux 狀態管理工具,與react沒有任何關係,其他ui框架也可以使用redux react redux react外掛程式,作用 方便在react專案中使用redux r...
如何優雅地在React專案中使用Redux
首先我們會用到哪些框架和工具呢?ui框架 狀態管理工具,與react沒有任何關係,其他ui框架也可以使用redux react外掛程式,作用 方便在react專案中使用redux 中介軟體,作用 支援非同步action tips 與redux無關的目錄已省略 src store redux目錄 ac...