react redux

在react中使用redux入门。
基本的例子使用redux管理react的状态。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Hello React!</title>
<script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
<script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
<script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
<script src="https://cdn.bootcss.com/redux/4.0.1/redux.js"></script>
</head>
<body>

<div id="example"></div>
<script type="text/babel">
    const initialState = {
        cart: [
            {
                product: 'bread 700g',
                quantity: 2,
                unitCost: 90
            },
            {
                product: 'milk 500ml',
                quantity: 1,
                unitCost: 47
            }
        ]
        }
    const ADD_TO_CART = 'ADD_TO_CART'

    const renducer = function (state=initialState, action) {
        switch (action.type) {
            case ADD_TO_CART:
                return {
                    ...state,
                    cart:[...state.cart, action.payload],
                }
        
            default:
                return state;
                break;
        }
    }
    const store = Redux.createStore(renducer)
    
    //class声明组件
    class ClassComponent extends React.Component {

        addToCart(product, quantity, unitCost){
            store.dispatch({
                type:ADD_TO_CART,
                payload:{
                    product, quantity, unitCost
                }
            })
        }

        render(){
            return (
                <div>
                    <h1>{this.props.v1}--{store.getState().cart.length}</h1>
                    <button onClick={()=>{this.addToCart('coffee1',1,100)}}>addToCart1</button>
                    <button onClick={()=>{this.addToCart('coffee2',2,200)}}>addToCart2</button>
                </div>
            )
        }
    }

    const render = ()=>{
        ReactDOM.render(
            <div>
                <ClassComponent v1={'hello redux'} />
                <button onClick={()=>{console.log(store.getState())}}>getState</button>
            
            </div>,
            document.getElementById('example')
        );
    }
    render()

    let unsubscribe = store.subscribe(() =>{
        render();
        console.log(store.getState());
    });

    //解除监听
    // unsubscribe();
</script>

</body>
</html>

参考文档:
Redux 入门教程
Redux入门教程(快速上手)

猜你喜欢

转载自blog.csdn.net/Cribug8080/article/details/89308508
今日推荐