自己按照教程手敲了一遍redux简单教程,最后终于通过了,纪念一下。
Notice
- 需要用到loadsh的deepclone功能。
- 从state复制出nextState之后,直接在nextState上操作数据。
var nextState=_.cloneDeep(state);
nextState.todos.push({"content":action.content});
return nextState;
<!DOCTYPE html>
<html>
<head>
<script src="./redux.min.js"></script>
<script src="https://cdn.jsdelivr.net/lodash/4.17.3/lodash.min.js"></script>
</head>
<body>
<button onclick="add()">+</button>
<button onclick="mini()">-</button>
<input type="text" id="content"><button onclick="push()">ok</button>
<script>
function incCreator(){
return {type:'INCREMENT'}
};
function decCreator(){
return {type:"DECREMENT"}
}
function pushCreator(content){
return {type:"PUSH",content:content}
}
var initState={
count:0,
todos:[]
}
function reducer(state,action){
//设置state初始值
state = state || initState;
switch(action.type){
case 'INCREMENT':
var nextState=_.cloneDeep(state)
nextState.count++;
return nextState;
case 'DECREMENT':
var nextState=_.cloneDeep(state)
nextState.count--;
return nextState;
case 'PUSH':
// var group=state.contentGroup;
var nextState=_.cloneDeep(state);
nextState.todos.push({"content":action.content})
return nextState;
default:
return state;
}
}
var store=Redux.createStore(reducer);
var state=store.getState();
function add(){
store.dispatch(incCreator())
console.log(store.getState())
}
function mini(){
store.dispatch(decCreator())
console.log(store.getState())
}
function push(){
var str=document.getElementById("content").value;
store.dispatch(pushCreator(str))
console.log(store.getState())
}
</script>
</body>
</html>
网友评论