12-connect

作者: 钢笔先生 | 来源:发表于2020-01-29 20:55 被阅读0次

    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.

    相关文章

      网友评论

        本文标题:12-connect

        本文链接:https://www.haomeiwen.com/subject/desbthtx.html