08.使用connect让react和redux更优雅的结合

  1. import React from 'react'
  2. import logo from './logo.svg'
  3. import './App.css'
  4. import { eat, hungry } from './stark.redux'
  5. import { connect } from 'react-redux'
  6. class App extends React.Component {
  7. render () {
  8. const {num, eat, hungry} = this.props
  9. return (
  10. <div className='App'>
  11. <header className='App-header'>
  12. <img src={logo} className='App-logo' alt='logo' />
  13. <p>
  14. redux完全指南】系列1:从入门到会用
  15. <br></br>
  16. hi gusy I am stark
  17. </p>
  18. <a
  19. className='App-link'
  20. href='https://shudong.wang'
  21. target='_blank'
  22. rel='noopener noreferrer'>跟着stark wang redux</a>
  23. <h2>stark wang 当前的体重为{num}斤</h2>
  24. <button onClick={() => {eat()}}>
  25. 吃了一坨山珍海味
  26. </button>
  27. <button onClick={() => {hungry()}}>
  28. 饿了一天
  29. </button>
  30. </header>
  31. </div>
  32. )
  33. }
  34. }
  35. // 把state挂在到 props 上面
  36. // const mapStateToProps = (state)=>{
  37. // return {num:state}
  38. // }
  39. // 把action 挂在到 props上面
  40. // const actionCreators = {eat,hungry}
  41. export default connect((state)=>{
  42. return {num:state}
  43. },{eat,hungry})(App)
  1. import React from 'react';
  2. import ReactDOM from 'react-dom';
  3. import './index.css';
  4. import App from './App';
  5. import * as serviceWorker from './serviceWorker';
  6. import { createStore } from 'redux'
  7. import { weight } from './stark.redux'
  8. import { Provider } from 'react-redux'
  9. const store = createStore(weight)
  10. // const render = () =>{
  11. ReactDOM.render(
  12. <Provider store={store}>
  13. <App />
  14. </Provider>,
  15. document.getElementById('root')
  16. );
  17. // }
  18. // render()
  19. // store.subscribe(render)
  20. // If you want your app to work offline and load faster, you can change
  21. // unregister() to register() below. Note this comes with some pitfalls.
  22. // Learn more about service workers: https://bit.ly/CRA-PWA
  23. serviceWorker.unregister();