React-redux 概述
react-redux 能夠使你的React組件從React store中很方便的讀取數(shù)據(jù)薇搁,并且向store中分發(fā)actions以此來更新數(shù)據(jù)
React-redux中重要的兩個成員
- Provider:這個組件能夠使你整個app都能獲取到store中的數(shù)據(jù)
渣磷。provider 包裹在根組件的最外層蒿秦,使所有的子組件都可以拿到 state
。provider 接收 store 作為 props漠酿,然后通過 context 往下傳遞拯钻,這樣react中任何組件都可以通過 context 獲取到 store - connect:這個方法能夠使組件跟store來進行關(guān)聯(lián)
。provider 內(nèi)部組件如果想要使用到 state 中的數(shù)據(jù)幔亥,就必須要 connect 進行一層包裹封裝,換一句話來說就是必須要被 connect 進行加強
玖像。connect 就是方便我們組件能夠獲取到 store 中的 state
React-redux的基本使用
安裝相關(guān)依賴
npm install redux react-redux
構(gòu)建 store 和 reducer
- 創(chuàng)建 reducer/index.js 文件紫谷,構(gòu)建reducer來響應(yīng) actions
const initState = {
status: false
}
exports.loverReducer = (state = initState, action) => {
switch (action.type) {
case 'send_love':
return {
status: true
}
case 'stop_love':
return {
status: false
}
default:
return state;
}
}
- 創(chuàng)建 store/index.js 文件齐饮,通過 createStore 方法捐寥,把我們的 reducer 傳入進來
import {createStore} from 'redux'
import {loverReducer} from '../reducer/index'
export default createStore(loverReducer)
- 在 app.js 中引入 store
// 導(dǎo)入store
import store from './store';
import { Provider } from 'react-redux'
class App extends React.Component {
render() {
return (
<Provider store={store}>
<div>
Hello world!
</div>
</Provider>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
搭建頁面結(jié)構(gòu)
- 創(chuàng)建一個組件,名字叫 ComA祖驱,里面放一個 button 按鈕
import React from 'react';
import { connect } from 'react-redux'
class Boy extends React.Component {
constructor(props){
super(props)
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
let status = this.props.status;
status?this.props.stopLove():this.props.sendLove();
}
render() {
let status = this.props.status;
return (
<button onClick={this.handleClick}>{status?'停止':'點擊'}發(fā)射</button>
)
}
}
const mapStateToProps = (state)=>{
return state
}
const mapDispatchToProps = (dispatch) => {
return {
sendLove: () => {
dispatch({
type: 'send_love'
})
},
stopLove: () => {
dispatch({
type: 'stop_love'
})
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Boy)
- 創(chuàng)建另一個組件握恳,名字叫 ComB,里面放一個 img捺僻,用來顯示圖片
import React from 'react';
import {connect} from 'react-redux';
import default_img from '../../../assets/images/send_love.jpg'
import dynamic_img from '../../../assets/images/send_love.gif'
class Girl extends React.Component {
render(){
let status = this.props.status
return(
<img src={status?dynamic_img:default_img} alt="" />
)
}
}
const mapStateToProps = (state)=>{
return state
}
export default connect(mapStateToProps)(Girl)
- 在 app.js 中引入兩個組件
import React from 'react'
import ReactDOM from 'react-dom';
import Boy from './pages/boy/index'
import Girl from './pages/girl/index'
// 導(dǎo)入store
import store from './store';
import { Provider } from 'react-redux'
class App extends React.Component {
render() {
return (
<Provider store={store}><div>
<Girl />
<Boy />
</div></Provider>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));