React 使用Redux简化数据传递实现及原理

一、概念

Redux简化数据传递

左侧是没有数据框架的传值,右侧则是使用Redux简化后传值。

所有值全部放在store管理,一个组件改变了store的内容,

其他组件就会感知到来取数据,间接实现数据传递功能。

二、Redux工作流程原理

图书馆借书例子

dispatch(action)  要借书的话

Store(state,action) 找到借书的人

Reducers 借书的人查看记录本

借书流程:dispatch→Store→Reducers→Store→Components

三、通过redux实现antdList的添加删除功能 

antd实现详解地址https://mp.csdn.net/postedit/102660910

创建store文件夹下 index 和 reducer

index.js 为 (store)

//store 存数据传递reducer处理
import {createStore} from 'redux';
import reducer from './reducer';

import React from "react";
//window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__() 为 redux devtools工具配置
const store=createStore(reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());

export default store;

reducer.js 为(处理store)


//reducer可以接收state但是不能修改state
//处理数据
//defaultState store默认值
const defaultState={
  inputValue:'123',
  list:[1,2]
}
//state上一次存储的数据
//action传过来改变的
export default (state=defaultState,action)=>{
 console.log(state,action);
 if(action.type==='change_input_value'){
   //复制一份数据
    const newState=JSON.parse(JSON.stringify(state))
    newState.inputValue=action.value;
    return newState;
 }
 //添加到列表
 if(action.type==='add_todo_item'){
   const newState=JSON.parse(JSON.stringify(state))
   newState.list.push(newState.inputValue);
   newState.inputValue='';
   return newState;
 }
  //删除点击列表内容
  if(action.type==='delete_todo_item'){
    const newState=JSON.parse(JSON.stringify(state))
    newState.list.splice(action.index,1);
    return newState;
  }
  return  state;
}

pages 创建antdList

import React from 'react';
import ShowList from '../components/ShowList';

export default function() {

  return (
    <div>
      <ShowList></ShowList>
    </div>
  );
}

components 创建 ShowList 提交和点击列表则触发(action)并且监听store返回的数据

import React,{ Component } from 'react';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import { Input,Button,List  } from 'antd';
import store from '../store';
//全局数据
// const data = [
//   'Racing car sprays burning fuel into crowd.',
//   'Japanese princess to wed commoner.',
//   'Australian walks 100km after outback crash.',
//   'Man charged over missing wedding girl.',
//   'Los Angeles battles huge wildfires.',
// ];

class showList extends Component{
  constructor(props){
    super(props);
    //创建数据
    console.log(store.getState());
    this.state=store.getState();
    this.handleInputChange=this.handleInputChange.bind(this);
    this.handleStoreChange=this.handleStoreChange.bind(this);
    this.handleBtnClick=this.handleBtnClick.bind(this);
    //监听返回组件的数据,并且同步数据。
    store.subscribe(this.handleStoreChange);
  }
  render(){
    return(
      <div style={{marginTop:'10px',marginLeft:'10px'}}>
        <div>
          {/*antd Input文本框*/}
          <Input value={this.state.inputValue} placeholder="Basic usage" style={{width:'300px', marginRight:'10px'}} onChange={this.handleInputChange}/>
          {/*antd button按钮*/}
          <Button type="primary" onClick={this.handleBtnClick}>提交</Button>
          {/*列表*/}
          <List style={{marginTop:'10px',width:'300px'}}
            bordered
            dataSource={this.state.list}
            renderItem={(item,index) => (
              <List.Item onClick={this.handleItemDelete.bind(this,index)}>
            {item}
              </List.Item>
            )}
          />
        </div>
      </div>

    )
  }
  //action
  handleInputChange(e){
    const action={
      type:'change_input_value',
      value:e.target.value
  };
    //action传递到store
    store.dispatch(action);
  }
  //点击提交添加到列表
  handleBtnClick(){
    const  action={
      type:'add_todo_item'
    };
    store.dispatch(action);
  }
  //删除列表点击的内容
  handleItemDelete(index){
    const action={
      type:'delete_todo_item',
      index:index
    }
    store.dispatch(action);
  }
  //同步数据
  handleStoreChange(){
    this.setState(store.getState)
  }
}
export default  showList;

优化版 通过 actionTypes.js 和 actionCreators.js 优化type和action

actionTypes.js

//定义常量
export const CHANGE_INPUT_VALUE='change_input_value';
export const ADD_TODO_ITEM='add_todo_item';
export const DELETE_TODO_ITEM='delete_todo_item';

actionCreators.js

import {CHANGE_INPUT_VALUE,ADD_TODO_ITEM,DELETE_TODO_ITEM} from '../store/actionTypes';

export const getInputChangeAction=(value)=>({
  type:CHANGE_INPUT_VALUE,
  value:value
});
export const getAddItemAction=()=>({
  type:ADD_TODO_ITEM
});
export const getDeleteItemAction=(index)=>({
  type:DELETE_TODO_ITEM,
  index:index
});
showList.js
import React,{ Component } from 'react';
import 'antd/dist/antd.css'; // or 'antd/dist/antd.less'
import { Input,Button,List  } from 'antd';
import store from '../store';
import {CHANGE_INPUT_VALUE,ADD_TODO_ITEM,DELETE_TODO_ITEM} from '../store/actionTypes';
import {getInputChangeAction,getAddItemAction,getDeleteItemAction} from '../store/actionCreators';
//全局数据
// const data = [
//   'Racing car sprays burning fuel into crowd.',
//   'Japanese princess to wed commoner.',
//   'Australian walks 100km after outback crash.',
//   'Man charged over missing wedding girl.',
//   'Los Angeles battles huge wildfires.',
// ];

class showList extends Component{
  constructor(props){
    super(props);
    //创建数据
    console.log(store.getState());
    this.state=store.getState();
    this.handleInputChange=this.handleInputChange.bind(this);
    this.handleStoreChange=this.handleStoreChange.bind(this);
    this.handleBtnClick=this.handleBtnClick.bind(this);
    //监听返回组件的数据,并且同步数据。
    store.subscribe(this.handleStoreChange);
  }
  render(){
    return(
      <div style={{marginTop:'10px',marginLeft:'10px'}}>
        <div>
          {/*antd Input文本框*/}
          <Input value={this.state.inputValue} placeholder="Basic usage" style={{width:'300px', marginRight:'10px'}} onChange={this.handleInputChange}/>
          {/*antd button按钮*/}
          <Button type="primary" onClick={this.handleBtnClick}>提交</Button>
          {/*列表*/}
          <List style={{marginTop:'10px',width:'300px'}}
            bordered
            dataSource={this.state.list}
            renderItem={(item,index) => (
              <List.Item onClick={this.handleItemDelete.bind(this,index)}>
            {item}
              </List.Item>
            )}
          />
        </div>
      </div>

    )
  }
  //action
  handleInputChange(e){
/*    const action={
      type:CHANGE_INPUT_VALUE,
      value:e.target.value
  };*/
    const action=getInputChangeAction(e.target.value);
    //action传递到store
    store.dispatch(action);
  }
  //点击提交添加到列表
  handleBtnClick(){
/*    const  action={
      type:ADD_TODO_ITEM
    };*/
    const action= getAddItemAction();
    store.dispatch(action);
  }
  //删除列表点击的内容
  handleItemDelete(index){
    // const action={
    //   type:DELETE_TODO_ITEM,
    //   index:index
    // }
    const action= getDeleteItemAction(index);
    store.dispatch(action);
  }
  //同步数据
  handleStoreChange(){
    this.setState(store.getState)
  }
}
export default  showList;

四、测试最终效果

发布了117 篇原创文章 · 获赞 32 · 访问量 16万+

猜你喜欢

转载自blog.csdn.net/qq_17025903/article/details/102628320