React redux

54 阅读1分钟

创建store

import {composeWithDevTools} from 'redux-devtools-extension'
// 把reducer引入到store中,并作为createStore函数的参数,让store知道有哪些公共数据
import reducer from './reducer';
// 定义一个数据的公共管理仓库
const store = createStore(reducer, composeWithDevTools());

export default store;

reducer处理数据然后返回一个新的state给store

const defaultState = {
    inputValue: '',
    list: []
}
// reducer可以接收state, 但是绝对不能改变state, 应该拷贝一份数据作为修改再返回给store自动修改
export default (state = defaultState, action) => {
    if(action.type === 'input_value') {
        const newState = JSON.parse(JSON.stringify(state))
        newState.inputValue = action.value
        return newState
    }
    if(action.type === 'click_add') {
        const newState = JSON.parse(JSON.stringify(state))
        newState.list.push(newState.inputValue)
        newState.inputValue = ''
        return newState
    }
    if(action.type === 'delete_item') {
        const newState = JSON.parse(JSON.stringify(state))
        newState.list.splice(action.index, 1)
        return newState
    }
    return state
}

action

// 创建的action 都要返回一个对象
export const getInputChangeAction = (value) => ({
    type: 'input_value',
    value: value
})

export const getClickAddAction = () => ({
    type: 'click_add'
})

export const getDeleteItemAction = (index) => ({
    type: 'delete_item',
    index: index
})

用法

通过store.getState()方法获取store的数据

 constructor(props) {
        super(props);
        console.log(store.getState());
        this.state = store.getState();
        // 只要store中的数据被改变, 这个函数就会被执行
        store.subscribe(this.handleChangeStore.bind(this))
        // this.state = {
        //     inputValue: '',
        //     list: []
        // };
    }
    
    
     // 增加
    handleClick() {
        // this.setState({
        //     list: [...this.state.list, this.state.inputValue],
        //     inputValue: ''
        // })
        // 通过dispatch派发action
        const action = getClickAddAction()
        store.dispatch(action)
    }
    // 删除
    handleItemDelete(index) {
        console.log(index)
        const action = getDeleteItemAction(index)
        store.dispatch(action)
        // 复制一个state数组,不要通过this.state去修改state中的数据
        // const list = [...this.state.list]
        // list.splice(index, 1)
        // this.setState({
        //     list: list
        // })
    }