React-redux
react-redux提供了了两个api
1. Provider 为后代组件提供store.
例子:将redux store中的值传入react组件
import {Provider} from "react-redux";
<Provider store={store}>
<App />
</Provider>
2. connect 为组件提供数据和变更方法.
将映射后的状态和方法注入到组件的props上,组件中就可以通过this.props.xx拿到想要的状态和方法了。
connect(mapStateToProps,mapDispatcjToProps)(注入的组件)
mapStateToProps: redux状态和组件状态的映射
mapDispatchToProps:redux方法和组件方法的映射
import React, { Component } from "react";
import { connect } from "react-redux";
class ReactReduxPage extends Component {
render() {
const { num, add } = this.props;
return (
<div>
<h3>ReactReduxPage</h3>
<p>{num}</p>
{/*<button onClick={() => this.props.dispatch({ type: "ADD" })}>add</button>*/}
<button onClick={add}>add</button>
</div>
);
}
}
const mapStateToProps = state => {
return {
num: state,
};
};
const mapDispatchToProps = {
add: () => {
return { type: "add" };
}
};
export default connect(
//mapStateToProps 把state映射到props
state => ({ num: state }),
//mapDispatchToProps 把dispatch映射到props
{
add: () => ({ type: "ADD" })
}
)(ReactReduxPage);