react之redux的使用

QM_姚丹發表於2019-06-10

這是上篇redux簡單介紹及寫法redux簡單使用
場景:我們實際專案開發中可能需要多個通知,比如購物車一個數量的通知,個人資訊變化的通知,那麼如果寫的。
在這裡插入圖片描述
主要思路其實就是在入口元件,將多個通知儲存合併一下就好了,具體程式碼示例如:

//這行程式碼用來建立儲存,儲存多個取值
let reducers = combineReducers({
    //用來計數的儲存
    counterReducer: addReduce,
    //用來獲取個人資訊的儲存
    personReducer: getPerson
});

然後取值元件的程式碼就需要更具那個key:personReducer

render() {
        return (
            <div>
                {/*這裡就得根據儲存器的key來獲取值了*/}
                姓名:{this.props.state.personReducer.pName}<br/>
                性別:{this.props.state.personReducer.pSex}<br/>
                年齡:{this.props.state.personReducer.pAge}<br/>
            </div>
        )
    }

下面是全部程式碼:
入口元件:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import RouterComponent from './router';
import * as serviceWorker from './serviceWorker';
import {createStore, combineReducers} from 'redux';
import {Provider} from 'react-redux';

//獲取計數器值
function addReduce(state = {amount: 0}, action) {
    console.log(action);
    switch (action.type) {
        case "add":
            return {amount: action.amount};
        case "reduce":
            return {amount: action.amount};
        //下面程式碼必須寫
        default:
            return state;
    }
}

//預設變數,賦值預設資料
let personState = {
    pName: '姓名',
    pSex: '性別',
    pAge: '年齡'
};

//獲取個人資訊
function getPerson(state = personState, action) {
    console.log(action);
    switch (action.type) {
        case "person":
            return {pName: action.name, pSex: action.sex, pAge: action.age};
        default:
            return state;
    }
}


//這行程式碼用來建立儲存,儲存多個取值
let reducers = combineReducers({
    //用來計數的儲存
    counterReducer: addReduce,
    //用來獲取個人資訊的儲存
    personReducer: getPerson
});
let store = createStore(reducers);

class Index extends React.Component {
    render() {
        return (
            //Provider 固定寫法 ,store={store}傳給各個元件
            <Provider store={store}><RouterComponent/></Provider>
        )

    }
}

ReactDOM.render(<Index/>, document.getElementById('root'));

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

個人資訊賦值:

import React from 'react';
import CounterComponent from './counter'
import {connect} from 'react-redux';

class PersonComponent extends React.Component {


    constructor(props) {
        super(props);
        this.state = {
            name: "",
            sex: "",
            age: 0
        }

    }

    getName(e) {
        this.setState({
            name: e.target.value
        });
    }

    getSex(e) {
        this.setState({
            sex: e.target.value
        });
    }

    getAge(e) {
        this.setState({
            age: e.target.value
        });

    }

    render() {
        return (
            <div>
                姓名:<input onChange={this.getName.bind(this)}/><br/>
                性別:<input onChange={this.getSex.bind(this)}/><br/>
                年齡:<input onChange={this.getAge.bind(this)}/><br/>
                <button onClick={()=>{
                    this.props.dispatch({type: 'person', name: this.state.name, sex: this.state.sex, age: this.state.age});
                }}>儲存</button>
            </div>
        )
    }
}

export default connect((state) => {
    return {
        state: state
    }
})(PersonComponent)

個人資訊取值:

import React from 'react';
import {connect} from 'react-redux';

class PersonMsgComponent extends React.Component {
    render() {
        return (
            <div>
                {/*這裡就得根據儲存器的key來獲取值了*/}
                姓名:{this.props.state.personReducer.pName}<br/>
                性別:{this.props.state.personReducer.pSex}<br/>
                年齡:{this.props.state.personReducer.pAge}<br/>
            </div>
        )
    }
}

export default connect((state) => {
    return {
        state: state
    }
})(PersonMsgComponent)

計數器賦值:

import React from 'react';
import CounterComponent from './counter'
import {connect} from 'react-redux';
import PersonComponent from "./person";
import PersonMsgComponent from './PersonMsg';

class IndexComponent extends React.Component {
    constructor(props) {
        super(props);
        this.number = 0;
    }

    btnAdd() {
        this.number++;
        this.props.dispatch({type: "add", amount: this.number});
    }

    btnReduce() {
        this.number--;
        this.props.dispatch({type: "reduce", amount: this.number});
    }


    render() {
        return (
            <div>
                <CounterComponent/>
                <div>計數器:{this.props.state.counterReducer.amount}</div>
                <div>
                    <button onClick={this.btnAdd.bind(this)}>+</button>
                    &nbsp;&nbsp;
                    <button onClick={this.btnReduce.bind(this)}>-</button>
                </div>
                <hr/>
                <div>輸入個人資訊:</div>
                <PersonComponent/>
                <div>獲取個人資訊:</div>
                <PersonMsgComponent/>
            </div>
        )
    }
}

//讓元件與redux關聯起來
export default connect((state) => {
    return {
        state: state
    }
})(IndexComponent);

計數器取值

import React from 'react';
import {connect} from 'react-redux';

class CounterComponent extends React.Component {
    render() {
        return (
            //取到值
            <div>子元件counter計數器:{this.props.state.counterReducer.amount}</div>
        )
    }
}
//將redux與CounterComponent元件關聯起來
export default connect((state) => {
        return {
            state: state
        }
    }
)(CounterComponent)

相關文章