基本概念
- store
- 存储数据的仓库
 - 使用 createStore 创建
 
 - state
- 数据的仓库当中存储的数据
 - 通过 store.getState() 获取 store 对应的快照
 
 - action
- 对象
 - 描述当前如何操作 state 对象的状态 ```jsx const addOne = { type: ‘ADD’, num: 1 }
 
 
const addTwo = { type: ‘ADD’, num: 2 }
const square = { type: ‘SQUARE’, }
4. dispatch- 唯一能更改 state 的方法- `store.dispatch(action)`5. reducer- 函数, 用来返回一个 state- 所有 action 的行为通过 reducer 来中转```jsxconst reducer = (state = 10, action) => {switch(action.type){case 'ADD':return state + action.num;case 'SQUARE':return state ** 2;default:return state;}}
操作示例
import React from "react";import ReactDOM from "react-dom";import { createStore } from "redux";const addOne = {type: "ADD",num: 1,};const addTwo = {type: "ADD",num: 2,};const square = {type: "SQUARE",};const reducer = (state = 10, action) => {switch (action.type) {case "ADD":return state + action.num;case "SQUARE":return state ** 2;default:return state;}};const store = createStore(reducer);function App() {return <div></div>;}ReactDOM.render(<App />, document.getElementById("root"));
使用 store.getState() 可以查看 state 的值
console.log(store.getState()); // 10,因为在 reducer 中定义初始值
使用 store.dispatch() 更改 state 状态
console.log(store.dispatch(addOne)); // {type: "ADD", num: 1} 返回 action 对象console.log(store.getState()); // 11console.log(store.dispatch(addTwo)); // {type: "ADD", num: 2} 返回 action 对象console.log(store.getState()); // 13console.log(store.dispatch(square)); // {type: "SQUARE"} 返回 action 对象console.log(store.getState()); // 169
