<React>Redux使用规范

200 阅读2分钟

Redux的使用

主要入口: src创建store文件夹并创建index.js

import { createStore } from "redux";
// 引用list的仓库
import listRedux from "./listRedux";
// 放到总仓库
const store = createStore(listRedux);

export default store;

store文件夹创建listActionTypes.js

// 创造Action规范
// 用于提示

export const  CHANGE_INPUT_VALUE = 'change_input_value';
export const INPUT_SUBMIT = 'input_submit';
export const DELETE_ITEM = 'delete_item';

store文件夹创建listActionCreators.js

// 操作listRedux动作合集

// 引用Action规范
// 操作listRedux动作合集

// 引用Action规范
import { CHANGE_INPUT_VALUE, INPUT_SUBMIT, DELETE_ITEM } from "./listActionTypes";
/**
 * input的值赋值到store的inputValue
 * @method getInputChangeAction
 * @param 输入的值
 */
export const getInputChangeAction = (value) => ({
    type: CHANGE_INPUT_VALUE,
    value
});
/**
 * inputValue添加到list里
 * @method getInputSubmit
 * @param inputValue
 */
export const getInputSubmit = (value) => ({
    type: INPUT_SUBMIT,
    value
});
/**
 * 删除item
 * @method listReduxDeleteItem
 * @param index 数组下标
 */
export const listReduxDeleteItem = (index) => ({
    type: DELETE_ITEM,
    index
});

store文件夹创建listRedux.js

因为会用到很多redux、做个简单的区分、防止混淆
// 处理list的Redux

// 引用规范
import { CHANGE_INPUT_VALUE, INPUT_SUBMIT, DELETE_ITEM } from "./listActionTypes";
// 默认值
let defaultState = {
   inputValue: '',
   list: [ '测试1', '测试2']
};


export default (state = defaultState, action) => {
   // input修改值
   if(action.type === CHANGE_INPUT_VALUE){
       const newState = JSON.parse(JSON.stringify(state));
       newState.inputValue = action.value;
       // 替换掉原来的值
       return newState;
   }
   // input提交
   if(action.type === INPUT_SUBMIT){
       const newState = JSON.parse(JSON.stringify(state));
       newState.list.push(action.value);
       newState.inputValue = '';
       return  newState
   }
   // item删除
   if (action.type === DELETE_ITEM){
       let newState = JSON.parse(JSON.stringify(state));
       newState.list.splice(action.index, 1);
       return newState;
   }
   return state;
}

todoList子组件:input 组件使用store

import React, { Component } from "react";
import { Input } from 'antd';
// 引用store
import store from "../../../store";
// 引用storeAction
import { getInputChangeAction } from "../../../store/listActionCreators";

class ListInput extends  Component{
   constructor(props) {
       super(props);
       // getState获取store的值
       this.state = store.getState();
       // subscribe监听store每次修改
       store.subscribe(this.listenStoreChange)

   }
   // 监听
   listenStoreChange = () =>{
       this.setState(store.getState());
   };
   // 输入input
   inputChange(event){
       // redux操作
       const action = getInputChangeAction(event.target.value);
       // 发送
       store.dispatch(action)
   };
   render() {
       let { inputValue } = this.state;
       return(
           <Input
               placeholder="测试"
               value={ inputValue }
               onChange={(event) => this.inputChange(event)}
           />
       )
   }
}
export default  ListInput;

todoList子组件:Li 组件使用store

import React, { Component } from "react";
import store from "../../../store";
import  { listReduxDeleteItem } from '../../../store/listActionCreators';
class ListLi extends Component{
   liClick() {
       console.log(this.props.index);
       // 使用store
       let action = listReduxDeleteItem(this.props.index);
       // 发送
       store.dispatch(action);
   };
   render() {
       const { item } = this.props;
       return(
           <li onClick={() => this.liClick()}>
               {item}
           </li>
       )
   }
}
export default ListLi

todoList父组件: List组件使用store

import React, { Component } from "react";
import ListInput from "./components/ListInput";
import ListLi from './components/ListLi'
import { Card, Button, notification } from "antd";
import store from "../../store";
import { getInputSubmit } from "../../store/listActionCreators";


class Index extends Component{
   constructor(props) {
       super(props);
       this.state = store.getState();
       // subscribe监听store每次修改
       store.subscribe(this.listenStoreChange)
   };
   // 提示
   openNotification = () => {
       notification.open({
           message: '提示',
           description:
               '输入不可为空哦~',
           onClick: () => {
               console.log('Notification Clicked!');
           },
       });
   };
   // 监听
   listenStoreChange = () => {
       this.setState(store.getState());
   };
   // 增加
   addItem = () => {
       const { inputValue } = this.state;
       if(!inputValue){
           this.openNotification();
           return;
       }
       const action = getInputSubmit(inputValue);
       store.dispatch(action);
   };

   render() {
       let { list } = this.state;
       const listLi = list.map((item, index) => {
           return (
               <ListLi key={index} item={item} index={index}  />
           )
       });
       const noLi = '暂无更多';
       return (
           <div style={{width: '100%'}}>
               <Card title='todo' style={{marginBottom: '30px'}}>
                   <h3>List2 Redux</h3>
                   <ListInput />
                   <Button type="primary" style={{marginTop: '20px'}} onClick={this.addItem}>添加</Button>
               </Card>
               <Card title='列表' style={{marginBottom: '30px'}}>
                   <ul>
                       {
                           list.length > 0 ? listLi : noLi
                       }
                   </ul>
               </Card>

           </div>
       )
   }
}
export  default  Index