07.redux与react配合使用

stark.redux.js

  1. import { createStore } from 'redux'
  2. const EAT = 'eat'
  3. const HUNGRY = 'hungry'
  4. // reducer
  5. export const weight = (state = 160 , action) => {
  6. switch (action.type) {
  7. case EAT:
  8. return state + 10
  9. case HUNGRY:
  10. return state - 10
  11. default:
  12. return 160
  13. }
  14. }
  15. // action
  16. export const eat = () => {
  17. console.log('stark wang 正在吃山珍海味')
  18. return {type: EAT}
  19. }
  20. export const hungry = () => {
  21. console.log('饿了一天')
  22. return {type: HUNGRY}
  23. }

App.js

  1. import React from 'react'
  2. import logo from './logo.svg'
  3. import './App.css'
  4. import { eat, hungry } from './stark.redux'
  5. class App extends React.Component {
  6. render () {
  7. const store = this.props.store
  8. const num = store.getState()
  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={() => {store.dispatch(eat())}}>
  25. 吃了一坨山珍海味
  26. </button>
  27. <button onClick={() => {store.dispatch(hungry())}}>
  28. 饿了一天
  29. </button>
  30. </header>
  31. </div>
  32. )
  33. }
  34. }
  35. export default App

index.js

  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. const store = createStore(weight)
  9. const render = () =>{
  10. ReactDOM.render(<App store={store} />, document.getElementById('root'));
  11. }
  12. render()
  13. store.subscribe(render)
  14. // If you want your app to work offline and load faster, you can change
  15. // unregister() to register() below. Note this comes with some pitfalls.
  16. // Learn more about service workers: https://bit.ly/CRA-PWA
  17. serviceWorker.unregister();