React-redux 概述
react-redux 能够使你的React组件从React store中很方便的读取数据,并且向store中分发actions以此来更新数据
React-redux中重要的两个成员
- Provider:这个组件能够使你整个app都能获取到store中的数据
。provider 包裹在根组件的最外层,使所有的子组件都可以拿到 state
。provider 接收 store 作为 props,然后通过 context 往下传递,这样react中任何组件都可以通过 context 获取到 store - connect:这个方法能够使组件跟store来进行关联
。provider 内部组件如果想要使用到 state 中的数据,就必须要 connect 进行一层包裹封装,换一句话来说就是必须要被 connect 进行加强
。connect 就是方便我们组件能够获取到 store 中的 state
React-redux的基本使用
安装相关依赖
npm install redux react-redux
构建 store 和 reducer
- 创建 reducer/index.js 文件,构建reducer来响应 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;
}
}
- 创建 store/index.js 文件,通过 createStore 方法,把我们的 reducer 传入进来
import {createStore} from 'redux'
import {loverReducer} from '../reducer/index'
export default createStore(loverReducer)
- 在 app.js 中引入 store
// 导入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'));
搭建页面结构
- 创建一个组件,名字叫 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?'停止':'点击'}发射</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)
- 创建另一个组件,名字叫 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'
// 导入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'));