如果打算用 react 写一个web应用,需要搭配 redux 作为状态管理 。
connect:
redux可以把状态传入组件内依靠的就是connect:
import React , { Component } from 'react';
import { connect } from 'react-redux';
class Home extends Component {
constructor(props){
super(props);
}
render(){
return (
<div>{this.props.mdFourData}</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
return {
mdFourData: state.mdFourData
}
}
export default connect(mapStateToProps)(Home)
在上面的代码中,通过connect就可以将state.mdFourData传入到Home组件中。
dispatch:
dispatch 可以用来发送 action ,可以是异步操作也可以是普通操作,主要是用来改变state状态树;
Home.js
import React , { Component } from 'react';
import { connect } from 'react-redux';
import { add } from './action'
class Home extends Component {
constructor(props){
super(props);
this.state = {
count: 0
}
}
handleClick(){
let count = this.state.count;
count++;
this.setState({count});
this.props.addData(count);
}
render(){
return (
<div>
<button onClick={this.handleClick}>点击</button>
{this.props.mdFourData}
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
return {
mdFourData: state.mdFourData
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
addData: (args) => {
dispatch(add(args))
}
}
}
export default connect(mapStateToProps , mapDispatchToProps)(Home);
接下来是使用redux连接起来:
action.js
export const add = (args) => {
return {
type: 'add',
payload: args
}
}
reduce.js
export const reduce = ( state = {count: 0} ,action) => {
switch(action.type){
case 'add':
return {...state , count: action.payload }
default:
return {...state}
}
}
store.js
在这里引入了中间件 redux-thunk , redux-promise ,主要是处理 dispatch( action ),使用了中间件,action可以是 function 或者 pomise 对象
import { createStore , applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import promiseMiddlewarefrom 'redux-promise';
import { reduce } from './reduce';
const store = createStore(
reduce ,
applyMiddleware(thunk ,promiseMiddlewarefrom )
);
export default store;
index.js
import React ,{ Component } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import Home from './Home';
ReactDOM.render(
<Provider store={store}>
<Home></Home>
</Provider>
);