一個(gè)簡(jiǎn)單的react-redux小demo

學(xué)了一段時(shí)間ReactRedux基礎(chǔ)后,終于手癢癢要自己來碼demo了!
從頭順一遍,理清思路!GO!

頁面瀏覽

剛初始化的頁面

點(diǎn)擊了6次Click Me按鈕,4次Say Hello按鈕

一、安裝

1.在安裝好node.js以及 npm后,在全局安裝好create-react-app后,就可以用這個(gè)命令在當(dāng)前目錄創(chuàng)建指定名字的react項(xiàng)目:

create-react-app react-demo
cd react-demo
yarn start  // 或者是 npm run start

2.安裝其他依賴(推薦用淘寶鏡像)

cnpm i react-redux --s
cnpm i redux --s

二、新建目錄

這是我的目錄結(jié)構(gòu),都放在src下
  • components // 用來放所有的組件
  • redux // 用來放所有的redux文件,再細(xì)分兩個(gè)目錄
    • actions // 用來放redux的所有actions
    • reducers // 用來放redux的所有reducers ,通過index.js來結(jié)合所有的reducers
  • static // 用來放所有的靜態(tài)資源(圖片、樣式等)
  • utils // 用來放一些工具(暫時(shí)沒用到,把creat-react-app中產(chǎn)生的別的js放進(jìn)去了)
  • views // 用來放所有頁面
  • index.js // 這個(gè)不用說了吧,大佬

三、編寫組件

在 src/components/ 下新建一個(gè) Couter.js :


目錄結(jié)構(gòu)

想實(shí)現(xiàn)的功能:
兩個(gè)按鈕,一個(gè)在點(diǎn)擊的時(shí)候會(huì)自身加1,一個(gè)在點(diǎn)擊的時(shí)候加 'hello!'。所以有:
兩個(gè)事件:onIncreaseClickonSayHello
兩個(gè)參數(shù): count、 hello

import React from 'react'
import { Component } from 'react'

class Counter extends Component {
    constructor(props) {
        super(props)
        this.state = {
            count: props.count || 0,
            hello: props.hello || ''
        }
    }

    render() {
        const { count, hello, onIncreaseClick, onSayHello } = this.props
        // console.log(this.props)
        return (
            <div className="my-button">
                <button onClick={onIncreaseClick}>Click Me</button>
                <button onClick={onSayHello}>Say Hello</button>
                <div>
                    <div>Click Count: {count}</div>
                    <div>Say: {hello}</div>
                </div>
            </div>
        )
    }

    propTypes: {
        count: propTypes.number.isRequired,
        hello: propTypes.string.isRequired,
        onIncreaseClick: PropTypes.func.isRequired,
        onSayHello: PropTypes.func.isRequired
    }
}

export default Counter

四、編寫redux

1.寫actions
  • 因?yàn)橛袃蓚€(gè)事件,所以有兩個(gè)action。
  • 在src/redux/actions/下新增兩個(gè)js文件:


    目錄
// increase.js
const increaseAction = {
    type: 'increase'
}

export default increaseAction
// hello.js
const sayHelloAction = {
    type: 'sayHello'
}

export default sayHelloAction
2.寫reducers

在 src/redux/reducers 目錄下創(chuàng)建一個(gè)組件Counterreduxreducer--counter.js,一個(gè)匯總所有reducersindex.js

image.png

// counter.js
export default function counterReducer(state = initialState, action) {
    // console.log(state, 'counter')

    switch (action.type) {
        case 'increase': return Object.assign({}, state, {
            count: state.count + 1
        });
        case 'sayHello':  return Object.assign({}, state, {
            hello: state.hello + 'hello! '
        });
        default: return state;
    }
}

const initialState = {
    count: 0,
    hello: 'I say '
}
// index.js
import { combineReducers } from 'redux'
import counter from './counter'

const reducers = combineReducers({
    counter
})

export default reducers

五、編寫頁面

簡(jiǎn)簡(jiǎn)單單就一個(gè)頁面,在 src/views/ 下新建一個(gè)App.js:


目錄
import React from 'react';
import { connect } from 'react-redux'
import Counter from '../components/Counter'
import increaseAction from "../redux/actions/increase";
import sayHelloAction from "../redux/actions/hello";

// Map Redux State to component props
const mapStateToProps = state => {
    // console.log(state, 123)
    return {
        count: state.counter.count,
        hello: state.counter.hello
    }
}
// Map Redux actions to component props
const mapDispatchToProps = dispatch => {
    return {
        onIncreaseClick: () => {
            dispatch(increaseAction)
        },
        onSayHello: () => {
            dispatch(sayHelloAction)
        }
    }
}
// Connect component
const App = connect(
    mapStateToProps,
    mapDispatchToProps
)(Counter)

export default App;

六、渲染出來

修改 src/index.js:

import React from 'react';
import ReactDOM from 'react-dom';
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import App from './views/App'
import reducers from './redux/reducers'
import './static/index.css';
// import registerServiceWorker from './utils/registerServiceWorker';

// store
const store = createStore(reducers)

ReactDOM.render(
    <Provider store={store}>
        <App/>
    </Provider>, document.getElementById('root'));
// registerServiceWorker();

完整項(xiàng)目代碼:

https://github.com/LiaPig/react-redux-demo.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容