1. 程式人生 > 實用技巧 >react-redux的使用

react-redux的使用

react-redux的使用,前面已經介紹了redux的使用(https://www.cnblogs.com/cupid10/p/13629368.html)

redux:

  • 它是專門用來建立倉庫,你可以叫它為store
  • 通過redux庫裡的createStore方法來建立倉庫
  • 值得傲嬌的是redux並不像vuex那樣,必須依賴vue而使用,單獨拿出來也可以使用

那麼,問題來了?

  • react-redux又是做什麼的?
    • 首先,從名字上來看,就應該能瞭解,這是結合react與redux一起來使用的
    • 其次,是重點,它是用來連線react元件store倉庫的橋樑

下面要看下它的使用流程

首先安裝 npm i redux react-redux --save

或者 yarn add react-redux

在入口檔案index.js中從react-redux中引入Provider

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {Provider} from 'react-redux'
import store from './store'
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

store/index.js檔案

import {createStore} from 'redux';
import reducer from './reducer';
const store  = createStore(reducer)
export default store

store/reducer.js檔案

let state = {
    list: [
        { id: 1, title: "星期一", isFinished: true },
        { id: 2, title: "星期二", isFinished: false }
    ]
}
const reducer = (prevState = state, action) => {
    let newState = { ...prevState }
    switch (action.type) {
        case "addList":
            newState.list = newState.list.slice()
            newState.list.push({
                id: handleList.getId(newState.list),
                title: action.title
            })
            break;
        case "changeList":
            newState.list = handleList.changeList(newState.list, action.id)
            break;
        case "removeList":
            newState.list = handleList.removeList(newState.list, action.id)
            break;
        default:
            break;
    }
    return newState
}
const handleList = {
    getId(list) {
        list = list.slice()
        if (list.length === 0) return 1
        return list.sort((a, b) => {
            return b.id - a.id
        })[0].id + 1
    },
    changeList(list, id) {
        list = list.slice()
        for (let i = 0; i < list.length; i++) {
            if (list[i].id === id) {
                list[i].isFinished = !list[i].isFinished
            }
        }
        return list
    },
    removeList(list, id) {
        list = list.slice()
        return list.filter((item) => {
            console.log(item)
            if (item.id === id) {
                return false
            }
            return true
        })

    }

}
export default reducer

store/actionCreators.js檔案

import store from './index'
const actions = {
    addList(title) {
        let action = {
            type: "addList",
            title
        }
        //redux中用 store.dispatch(action)進行派發,react-redux交給元件自己配發
        return action
    },
    changeList(id) {
        let action = {
            type: "changeList",
            id
        }
        return action
    },
    removeList(id) {
        let action = {
            type: "removeList",
            id
        }
        return action
    },
}
export default actions

TodoInput.js

import React, { Component } from 'react'
import actions from '../store/actionCreators'
import { connect } from 'react-redux'
class TodoInput extends Component {
    handleKey = (e) => {
        if (e.keyCode === 13) {
            this.props.addList(e.target.value)
            e.target.value = ""
        }
    }
    render() {
        return (
            <div>
                <input placeholder="請輸入內容" onKeyUp={this.handleKey}></input>
            </div>
        )
    }
}
// 這個方法可以將所有更改redux狀態的方法全部掛載到ui元件的props上去
// const mapDispatchToProps = dispatch => {
//     return {
//         addList: function (title) {
//             let action = actions.addList(title)
//             dispatch(action)
//         }
//     }
// }
// 相當於把左右actions的方法全都繫結到ui元件的props,並且自動將其派發給redux
const mapDispatchToProps = actions
export default connect(null, mapDispatchToProps)(TodoInput)

Redux元件

import React, { Component } from 'react'
// import store from '../store'
import actions from '../store/actionCreators'
import TodoInput from './TodoInput'
import {connect} from 'react-redux'
class Redux extends Component {
    // redux需要使用store.subscribe獲取state資料的變化
    // constructor() {
    //     super()
    //     this.state = {
    //         list: []
    //     }
    // }
    // setList() {
    //     this.setState({
    //         list: store.getState().list
    //     })
    // }
    // componentDidMount() {
    //     this.setList()
    //     store.subscribe(() => {
    //         this.setList()
    //     })
    // }
    handleCheck = (id) => {
        this.props.changeList(id)
    }
    remove = (id) => {
        this.props.removeList(id)
    }
    render() {
        let { list } = this.props;
        return (
            <div>
                <TodoInput />
                {
                    list.map(item => {
                        return <li key={item.id} style={{textDecoration:item.isFinished ? 'line-through':'none'}}><input type="checkbox" checked={item.isFinished} onChange={this.handleCheck.bind(this, item.id)}  /> {item.title}
                            <button onClick={this.remove.bind(this, item.id)}>刪除</button>
                        </li>
                    })
                }
            </div>
        )
    }
}
const mapStateToProps = (state)=>{
        return{
            list:state.list
        }
}
export default connect(mapStateToProps,actions)(Redux)

//const mapDispatchToProps = actions
//export default connect(mapStateToProps,mapDispatchToProps)(Redux)