【js】Redux基本原理和使用

Redux不是说任何的应用都要用到它,如果遇到了react解决不了得问题,可以考虑使用它。

例如:

用户的使用方式复杂
不同身份的用户有不同的使用方式(比如普通用户和管理员)
多个用户之间可以协作
与服务器大量交互,或者使用了WebSocket
View要从多个来源获取数据

Redux的设计思想:

(1)Web 应用是一个状态机,视图与状态是一一对应的。
(2)所有的状态,保存在一个对象里面。

Redux的基本概念和api:

1. Store 保存数据的地方。整个应用只能有一个store。 函数createStore来生成store。

2. state store包含数据的集合。store.getState() 来得到当前时刻的state. Redux规定一个state对应一个view。state相同则view相同。

3.Action view与state不能直接交互,view发出通知给Action 表示state将要变化。 其中type属性是必然的。

  store.dispatch()是view发出action的唯一方法。

4.Reducer:state收到action之后会生成一个新的state,这个计算过程叫做reducer..Reducer是一个函数,他接受action和当前的state来作为参数,返回一个新的state

Redux工作流程:

1. 首先用户发出action。 store.dispatch(action);

2.然后,Store 自动调用 Reducer,并且传入两个参数:当前 State 和收到的 Action。 Reducer 会返回新的 State 。 let nextState = todoApp(previousState, action);

3.State 一旦有变化,Store 就会调用监听函数。
// 设置监听函数
store.subscribe(listener);
listener可以通过store.getState()得到当前状态。如果使用的是 React,这时可以触发重新渲染 View。

function listerner() {
  let newState = store.getState();
  component.setState(newState);   
}

计数器的实例:

const Counter = ({value}) =>(
  <h1>{value}</h1>
  <Button onClick={onIncrement}>+</Button>
  <Button onClick={onDecrement}>-</Button>
 );


const reducer = (state=0, action) => {
  switch(action.type) {
    case 'INCERMENT': return state+1;
    case 'DECREMENT': return state-1;
    default: return state;
  }
}


//传入reducer则store.dispatch会自动触发Reducer的自动执行
const sotre = createStore(reducer);


const render = () => {
  ReactDom.render(
    <Counter
      value={store.getState()}
      onIncrement={() => store.dispatch({type:'INCREMENT'})}
      onDecrement={() => store.dispatch({type:'DECREMENT'})}
    />,
  document.getElementById('root')
  );
}


render();
//state状态发生变化时 会自动调用render
store.subscribe(render);


---------------------
作者:lixuce1234
来源:CSDN
原文:https://blog.csdn.net/lixuce1234/article/details/74295691

原文地址:https://www.cnblogs.com/yeujuan/p/10101825.html