redux 入門教程1

新手看網上一些redux文章,很容易被那些概念搞糊塗,本人照着官方例子打算寫個系列新手教程,你們能夠參考下,轉載請註明出處html

 redux 理念詳解:http://zhuanlan.zhihu.com/haochuan/20641377react

教程1即沒有用到react,也沒有用到npm這些東西,很是適合你們從本質上理解redux。npm

1.加載redux.js  <script src="https://npmcdn.com/redux@latest/dist/redux.min.js"></script>redux

2.html函數

<div id="container">
<button onClick="select('a')">click a</button>
<button onClick="select('b')">click b</button>
<button onClick="select('c')"> click c</button>
<div id="show"> </div>
</div>this

 

3.jsspa

//handleStore至關於控制store的一個函數,也就是reducerscdn

function handleStore(store, action){
if(typeof store === undefined){
return false;
}htm

switch(action.type){
case 'a': return 'this is A'; break;
case 'b': return'this is B'; break;
case 'c': return 'this is C'; break;
default: return 'this is None'; break;
}
}blog

 

//store經過createStore建立
var store = Redux.createStore(handleStore);

//經過subscribe能夠觀察到store改變

store.subscribe(function(){
document.getElementById('show').innerHTML = store.getState().toString();
});

 

//初始化執行

select('');

 

function select(item){
store.dispatch({
type: item
});
}

 

 

全部源碼:

<!DOCTYPE html>
<html>
  <head>
    <title>Redux basic example</title>
    <script src="https://npmcdn.com/redux@latest/dist/redux.min.js"></script>
  </head>
  <body>
    <div id="container">
        <button onClick="select('a')">click a</button>
        <button onClick="select('b')">click b</button>
        <button onClick="select('c')"> click c</button>
        <div id="show"> </div>
    </div>


    <script>
        function handleStore(store, action){
            if(typeof store === undefined){
                return false;
            }

            switch(action.type){
                case 'a': return 'this is A'; break;
                case 'b': return'this is B'; break;
                case 'c': return 'this is C'; break;
                default: return 'this is None'; break;
            }
        }
        var store = Redux.createStore(handleStore);

        store.subscribe(function(){
            document.getElementById('show').innerHTML = store.getState().toString();
        });

        select('');

        function select(item){
            store.dispatch({
                type: item
            });
        }
    </script>


  </body>
  </html>
相關文章
相關標籤/搜索