redux-1
Posted 张若昀的小迷妹
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了redux-1相关的知识,希望对你有一定的参考价值。
一、.redux工作流程
1.用户发出action
store.dispatch(action);
2.store自动调用reducer,并传入2个参数:当前state和收到的action,reducer会返回新的state
let nextState = todoApp(previousState, action);
eg:
const reducer =(state=0,action)=>{
switch(action.type){
case \'INCREMENT\':return state+1;
case \'DECREMENT\':return state-1;
default:return state;
}
};
const store=createStore(reducer);
3.state一旦有变化,store就会调用监听函数
store.subscribe(listener);
listener可以通过store.getState()得到当前状态
eg:
const render=()=>{
ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={()=>store.dispatch({type:\'INCREMENT\'})}
onDecrement={()=>store.dispatch({type:\'DECREMENT\'})}/>,
document.getElementById("root")
);
};
store.subscribe(render);
二、redux实例--点击计数
const Counter = ({ value, onIncrement, onDecrement }) => (
<div>
<h1>{value}</h1>
<button onClick={onIncrement}>+</button>
<button onClick={onDecrement}>-</button>
</div>
);
const reducer = (state = 0, action) => {
switch (action.type) {
case \'INCREMENT\': return state + 1;
case \'DECREMENT\': return state - 1;
default: return state;
}
};
const store = createStore(reducer);
const render = () => {
ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={() => store.dispatch({type: \'INCREMENT\'})}
onDecrement={() => store.dispatch({type: \'DECREMENT\'})}
/>,
document.getElementById(\'root\')
);
};
render();
store.subscribe(render);
<div>
<h1>{value}</h1>
<button onClick={onIncrement}>+</button>
<button onClick={onDecrement}>-</button>
</div>
);
const reducer = (state = 0, action) => {
switch (action.type) {
case \'INCREMENT\': return state + 1;
case \'DECREMENT\': return state - 1;
default: return state;
}
};
const store = createStore(reducer);
const render = () => {
ReactDOM.render(
<Counter
value={store.getState()}
onIncrement={() => store.dispatch({type: \'INCREMENT\'})}
onDecrement={() => store.dispatch({type: \'DECREMENT\'})}
/>,
document.getElementById(\'root\')
);
};
render();
store.subscribe(render);
三、基本概念
3.1store
Store 就是保存数据的地方,整个应用只能有一个 Store
import{createStore} from \'redux\';
const store=createStore(reducer);
其中,createStore接受另一个函数做参数生成store,reducer接收当前state和action生成新的state
3.2state
此时的state可以通过store.getState()得到
import {createStore} from \'redux\';
<
以上是关于redux-1的主要内容,如果未能解决你的问题,请参考以下文章