Time: 20200129
connect
函数会将组件连接到redux store
。
CakeContainer.js
import React from 'react'
import { buyCake } from '../redux'
import { connect } from 'react-redux'
function CakeContainer(props) {
return (
<div>
<h2>Number of Cakes {props.numOfCakes}</h2>
<button onClick={props.buyCake}>Buy Cake </button>
</div>
)
}
const mapStatetoProps = state => {
return {
numOfCakes: state.numOfCakes
}
}
const mapDispatchToProps = dispatch => {
return {
buyCake: () => dispatch(buyCake())
}
}
export default connect(
mapStatetoProps,
mapDispatchToProps)
(CakeContainer)
App.js
import React from 'react';
import './App.css';
import CakeContainer from './components/CakeContainer';
import { Provider } from 'react-redux'
import store from './redux/store'
function App() {
return (
<Provider store={store}>
<div className="App">
<CakeContainer />
</div>
</Provider>
);
}
export default App;
组件CakeContainer
连接到Store后,就可以通过props.xxx
获取映射到props
上的属性。
END.
网友评论