react结合redux的开发步骤
?一.第一步是介紹redux的工作流程邏輯解析圖:
二.第2步介紹下redux的應(yīng)用如下圖所示:
三. 第三步是讓redux和react-redux在項(xiàng)目中簡單應(yīng)用的例子
?第一步創(chuàng)建一個(gè)rootReducer.js文件如上圖所示
第二步如下圖,將這個(gè)rootReducer.js引入如果文件index.js,并且將它作為入?yún)魅隿reateStore中創(chuàng)建一個(gè)store;(createStore是來自于redux,在上面介紹redux中都有介紹)
然后創(chuàng)建一個(gè)store是通過如下方式:
import { createStore?} from 'redux';?
const store = createStore(rootReducer.js)
接下來我們需要從react-redux中引入provider;
import { Provider?} from 'react-redux';
然后我們需要將Provider形式將store注入到組件中來實(shí)現(xiàn)組件和store的通信,如下代碼
<Provider store={store}><App /></Provider>
最后綜合注入的代碼截圖如下:
四.第四步是如何在組件中如何連接store中的state狀態(tài)和修改state狀態(tài);
import { connect } from 'react-redux';
const mapStateToProps = (state) =>{return {posts: state.posts} }?export default connect(mapStateToProps)(組件的名稱)這樣組件中就可以直接將state中的狀態(tài)posts注入到props中,如此組件中就可以通過
this.props.posts直接用state中posts數(shù)據(jù)了,綜合如下圖所示:
?五.第五步就是如何子組件中更新state中的數(shù)據(jù)狀態(tài),如下圖中的mapDispatchToProps
const??mapDispatchToProps =?(dispatch) => {return {deletePost: dispatch({type: 'DELETE_POSTS',id: id})} }export default connect(mapStateToProps,mapDispatchToProps)(組件名稱)如上圖所示通過mapDispatchToProps(接受一個(gè)參數(shù)就是dispatch---用來派發(fā)action),組件中可以通過事件觸發(fā),在事件中調(diào)用上圖代碼中的deletePost函數(shù)來更新state中posts數(shù)據(jù)狀態(tài),下圖就是如何調(diào)用deletePost這個(gè)方法來達(dá)到更新state中posts數(shù)據(jù)的狀態(tài)
比如組件中有個(gè)button按鈕,通過button按鈕的點(diǎn)擊事件來調(diào)用deletePost,如下圖所示:
<button onclick={this.handleClick.bind(this)}></button>handleClick() {this.deletepost(this.props.product_id) }上述中說明了通過按鈕的點(diǎn)擊事件來觸發(fā)?mapDispatchToProps的deletePost事件來派發(fā)action,從而更新state中posts的數(shù)據(jù)。
這個(gè)只是我總結(jié)的部分學(xué)習(xí)react-redux和redux在項(xiàng)目中的應(yīng)用,如有問題歡迎大佬們指點(diǎn)一二,謝謝
總結(jié)
以上是生活随笔為你收集整理的react结合redux的开发步骤的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: NodeJS+Express+mySQL
- 下一篇: Ajax让网站与时俱进