store.dispatch 能修改 state 的值,但不能响应 UI,使用产生变化
import React from "react";
import ReactDOM from "react-dom";
import { createStore } from "redux";
import { addAction, squareAction } from "./actions/actions";
import math from "./reducers/math";
const store = createStore(math);
function App() {
return (
<div>
<p>{store.getState()}</p>
<button
onClick={() => {
store.dispatch(addAction(1));
console.log(store.getState());
}}
>
加1
</button>
<button
onClick={() => {
store.dispatch(addAction(2));
console.log(store.getState());
}}
>
加2
</button>
<button
onClick={() => {
store.dispatch(squareAction());
console.log(store.getState());
}}
>
乘方
</button>
</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
store.subscribe()
通过 store.subscribe 订阅让 UI 渲染,参数为一个渲染函数
import React from "react";
import ReactDOM from "react-dom";
import { createStore } from "redux";
import { addAction, squareAction } from "./actions/actions";
import math from "./reducers/math";
const store = createStore(math);
function App() {
return (
<div>
<p>{store.getState()}</p>
<button
onClick={() => {
store.dispatch(addAction(1));
}}
>
加1
</button>
<button
onClick={() => {
store.dispatch(addAction(2));
}}
>
加2
</button>
<button
onClick={() => {
store.dispatch(squareAction());
}}
>
乘方
</button>
</div>
);
}
function render() {
ReactDOM.render(<App />, document.getElementById("root"));
}
render();
store.subscribe(render);