最简的redux教程

自己按照教程手敲了一遍redux简单教程,最后终于通过了,纪念一下。

Notice

  1. 需要用到loadsh的deepclone功能。
  2. 从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>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容