最简单的React和Redux整合的例子

安装create-react-app
npm install -g create-react-app


创建项目
create-react-app reactreduxrouterdemo
cd reactreduxrouterdemo
安装第三方模块
npm install --save redux
npm install --save react-redux
npm install --save react-router


修改index.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';


//定义组件
class App extends Component{
    render() {
        const {text, onChangeText, onButtonClick} = this.props;
        return (
            <div>
                <h1 onClick={onChangeText}> {text} </h1>
                <button onClick={onButtonClick}>click me</button>
            </div>
        );
    }
}


//action
const changeTextAction = {
        type:'CHANGE_TEXT'
}
const buttonClickAction = {
        type:'BUTTON_CLICK'
}


//reducer
const initialState = {
    text: 'Hello'
}
const reducer = (state = initialState, action) => {
    switch (action.type) {
        case 'CHANGE_TEXT':
            return {
                text: state.text=='Hello' ? 'world':'Hello'
            }
        case 'BUTTON_CLICK':
            return {
                text: 'Hello world'
            }
        default:
            return initialState;
    }
}

//store
let store = createStore(reducer);

//映射Redux state到组件的属性
function mapStateToProps(state) {
    return { text: state.text }
}

//映射Redux actions到组件的属性
function mapDispatchToProps(dispatch){
    return{
        onButtonClick:()=>dispatch(buttonClickAction),
        onChangeText:()=>dispatch(changeTextAction)
    }
}

//连接组件
App = connect(mapStateToProps, mapDispatchToProps)(App)

//渲染组件
ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
)








这个例子大概是最简单的了, 而且每一步注释都非常清楚了。
运行工程npm start






源代码工程
https://github.com/chenhaifeng2016/reactreduxrouter



 
 

                
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值