React-Redux是Redux的官方React绑定库。它能够使你的React组件从Redux store中读取数据,并且向store分发actions以更新数据
安装
在你的React app中使用React-Redux:
npm install --save react-redux
或者
yarn add react-redux
Provider和connect
React-Redux 提供<Provider/>组件,能够使你的整个app访问到Redux store中的数据:
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import store from "./store";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
rootElement
);
React-Redux提供一个connect方法能够让你把组件和store连接起来。
通常你可以以下面这种方式调用connect方法:
import { connect } from "react-redux";
import { increment, decrement, reset } from "./actionCreators";
// const Counter = ...
const mapStateToProps = (state /*, ownProps*/) => {
return {
counter: state.counter
};
};
const mapDispatchToProps = { increment, decrement, reset };
export default connect(
mapStateToProps,
mapDispatchToProps
)(Counter);
网友评论