1.store
store保存数据的地方,可以看成一个容器,整个应用只能拥有一个store
Redux提供createStore函数用来生成store
import { createStore } from 'redux';
import reducer from './reducer'
const store = createStore(reducer );
//createStore函数接受另一个函数作为参数,返回新生成的store对象
2.State
一个 State 对应一个 View,通过与用户的交互,实现不同的状态,然后去渲染UI,这样就让用户的数据和界面保持一致了,state可以通过store.getState()拿到数据。
const state = store.getState();
3.Action
State只能在本组件中去初始化,并且 State只能被本组件去修改和仿问,不能被外部仿问和修改,用户不能直接修改State,State要发生变化时可以通过Action发起通知
Action是一个对象,type属性是必须的(type是一个字符串常量。如果两种类型相同,则它们必须严格等效(使用===),其他属性可以自由设置
const action = {
type: 'ADD_ITEM',
data:"add count"
};
4.Action Creator
View在发送消息时,有多少种消息就会创建多少Action,为了简便代码就可以定义一个函数来生成Aciton
const ADD_ITEM= 'ADD_ITEM';
const addAction = (value) => ({
type: ADD_ITEM,
value
})
5.store.dispatch()
store.dispatch()是 View 发出 Action 的唯一方法。
const action={
type: 'ADD_ITEM',
data:"add count"
}
store.dispatch(action);
store.dispatch(addAction ("add count")); //结合Action Creator
6.Reducer
Store 收到 Action 以后,必须给出一个新的 State,这样 View 才会发生变化。这种 State 的计算过程就叫做 Reducer。
Reducer 是一个函数,它接受 Action 和当前 State 作为参数,返回一个新的 State。
const count=0
function add(state = count, action) {
switch (action.type) {
case "ADD_ITEM":
let newState = JSON.parse(JSON.stringify(state)) //深度拷贝state
return newState+1
default:
return state
}
}
7.store.subscribe()
Store 允许使用store.subscribe方法设置监听函数,一旦 State 发生变化,就自动执行这个函数
store.subscribe(store.getState());
store.subscribe方法返回一个函数,调用这个函数就可以解除监听。
let unsubscribe = store.subscribe(() =>
console.log(store.getState())
);
unsubscribe();