美文网首页
react-redux

react-redux

作者: 现_状 | 来源:发表于2019-03-29 10:12 被阅读0次

    index.js

    import React from 'react';
    import ReactDom from 'react-dom';
    import {createStore, applyMiddleware,compose} from 'redux';
    import thunk from 'redux-thunk'
    import {Provider} from 'react-redux';
    import App from './App';
    import {counter} from './index.redux';
    
    //用来配置调试redux工具用
    const reduxDevtools = window.devToolsExtension?window.devToolsExtension():f=>f;
    //处理中间件applyMiddleware,组合函数用的compose
    const store =  createStore(counter,compose(applyMiddleware(thunk),reduxDevtools));
    
    ReactDom.render(
        <Provider store={store}>
            <App/>
        </Provider>,
        document.getElementById('root')
    )
    

    index.redux.js

    
    const ADD_GUN = '加机关枪';
    const REMOVE_GUN = '减机关枪';
    
    
    //reducer
    export function counter(state=0,action){
        switch(action.type){
            case ADD_GUN:
                return state+1
            case REMOVE_GUN:
                return state-1
            default:
                return 10        
        }
    }
    
    //action creator
    export function addGun(){
        return {type:ADD_GUN}
    }
    export function removeGun(){
        return {type:REMOVE_GUN}
    }
    export function addGunAsync(){
        return dispatch=>{
            setTimeout(()=>{
                dispatch((addGun()))
            },2000)
        }
    }
    

    App.js

    
    import React from "react";
    import { Button } from 'antd-mobile';
    import { connect } from "react-redux";
    import {addGun,removeGun,addGunAsync} from "./index.redux";
    
    
    class App extends React.Component{
        render(){
            return (
                <div>
                    <h1>现在有{this.props.num}</h1>
                    <Button onClick={this.props.addGun}>加一把</Button>
                    <Button onClick={this.props.removeGun}>减一把</Button>
                    <Button onClick={this.props.addGunAsync}>异步加一把</Button>
                </div>
            )
        }
    }
    const mapStatetoProps=(state)=>{
        return {num:state}
    }
    const actionCreators={addGun,removeGun,addGunAsync}
    App = connect(mapStatetoProps,actionCreators)(App)
    export default App;
    

    相关文章

      网友评论

          本文标题:react-redux

          本文链接:https://www.haomeiwen.com/subject/vxikbqtx.html