store.dispatch 能修改 state 的值,但不能响应 UI,使用产生变化

  1. import React from "react";
  2. import ReactDOM from "react-dom";
  3. import { createStore } from "redux";
  4. import { addAction, squareAction } from "./actions/actions";
  5. import math from "./reducers/math";
  6. const store = createStore(math);
  7. function App() {
  8. return (
  9. <div>
  10. <p>{store.getState()}</p>
  11. <button
  12. onClick={() => {
  13. store.dispatch(addAction(1));
  14. console.log(store.getState());
  15. }}
  16. >
  17. 1
  18. </button>
  19. <button
  20. onClick={() => {
  21. store.dispatch(addAction(2));
  22. console.log(store.getState());
  23. }}
  24. >
  25. 2
  26. </button>
  27. <button
  28. onClick={() => {
  29. store.dispatch(squareAction());
  30. console.log(store.getState());
  31. }}
  32. >
  33. 乘方
  34. </button>
  35. </div>
  36. );
  37. }
  38. ReactDOM.render(<App />, document.getElementById("root"));

store.subscribe()

通过 store.subscribe 订阅让 UI 渲染,参数为一个渲染函数

  1. import React from "react";
  2. import ReactDOM from "react-dom";
  3. import { createStore } from "redux";
  4. import { addAction, squareAction } from "./actions/actions";
  5. import math from "./reducers/math";
  6. const store = createStore(math);
  7. function App() {
  8. return (
  9. <div>
  10. <p>{store.getState()}</p>
  11. <button
  12. onClick={() => {
  13. store.dispatch(addAction(1));
  14. }}
  15. >
  16. 1
  17. </button>
  18. <button
  19. onClick={() => {
  20. store.dispatch(addAction(2));
  21. }}
  22. >
  23. 2
  24. </button>
  25. <button
  26. onClick={() => {
  27. store.dispatch(squareAction());
  28. }}
  29. >
  30. 乘方
  31. </button>
  32. </div>
  33. );
  34. }
  35. function render() {
  36. ReactDOM.render(<App />, document.getElementById("root"));
  37. }
  38. render();
  39. store.subscribe(render);