React-Redux

React-Redux

老赵(redux)能力用起来很麻烦,为了方便管理,使用魏和尚来负责连接

  • npm instal --save react-redux
  • 忘记subscribe,记住reducer、action和dispatch即可
  • react-redux提供Provider和connect两个接口来连接

react-redux具体使用

  • Provider组件在应用最外层,传入store即可,只用一次
  • connect负责从外部获取组件需要的参数
  • connect可以用装饰器的方式来写

index.js文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import {Provider} from 'react-redux';

// function render(){
// ReactDom.render(<App store={store} />,document.getElementById('root'))
// }
// render();

// store.subscribe(render);

ReactDom.render(
(<Provider store={store}>
<App />,
</Provider>)
document.getElementById('root')
)

App.js文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import React from 'react';
import {addGUN,removeGUN,addGunAsync} from './index.redux';
import {connect} from 'react-redux';

class App extends React.Component{
render(){
return (
<div>
<h1>现在有机枪{this.props.num}把</h1>
<button onClick={this.props.addGUN}>申请武器</button>
<button onClick={this.props.removeGUN}>上交武器</button>
<button onClick={this.props.addGunAsync}>拖两天申请武器</button>
</div>
)
}
}
//数据。参数是状态
const mapStateProps = (state) =>{
return {num:state}
}

const actionCreators = {addGUN,removeGUN,addGunAsync}

//属性和方法分别给到组件
App = connect(mapStateProps,actionCreators)(App);
export default App;

使用装饰器优化connect代码

  • npm install --save-dev babel-plugin-transform-decorators-legacy

  • 增加配置`”plugins”:[

    "transform-decorators-legacy"
    

    ]`

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//数据。参数是状态
// const mapStateProps = (state) =>{
// return {num:state}
// }

// const actionCreators = {addGUN,removeGUN,addGunAsync}

//属性和方法分别给到组
// App = connect(mapStateProps,actionCreators)(App);

@connect(
//你要state里什么属性放到props里
state=>({num:state}),
//你要什么方法,放到props里,自动dispatch
{addGUN,removeGUN,addGunAsync}
)
------ 本文结束 ------
0%