Redux之react-redux简单项目入门

一:效果图

Redux之react-redux简单项目入门_第1张图片

二:目录结构

        

注意:已经安装了react官方脚手架(进行修改)

Redux之react-redux简单项目入门_第2张图片

三:相关代码

1:index.js

import React from 'react';
import ReactDOM from 'react-dom';
import TodoList from './TodoList';

//第一步
import {Provider} from 'react-redux';//引入react-redux
import  store from './store/index';

//作用:把store提供给所有的组件实现store共享
const App=(
    store={store}>
        
        {/*这里面的组件都有能力获取store里的数据*/}
        {/**/}
        {/**/}
    
);
//
// ReactDOM.render(, document.getElementById('root'));
ReactDOM.render(App, document.getElementById('root'));

2:TodoList.js

import React,{Component} from  'react';


//第二步
import {connect} from 'react-redux';

class TodoList extends  Component{
     render(){
        return(
            
value={this.props.inputValue}//使用store传的值 onChange={this.props.changeInputValue} />
    { this.props.list.map((item,index)=>{ return
  • key={index} onClick={()=>this.props.deleteItem(index)}>{item}
  • }) }
) } } //规定映射条件 //store里的state映射到组件的props里 const mapStateToProps=(state)=>{ return { inputValue:state.inputValue,//inputValue是指组件this.props.inputValue,state.inputValue是指store里的inputValue list:state.list, } }; //把store.dispatch映射到组件的props上 const mapDispatchToProps=(dispatch)=>{ return { //把这个函数映射到组件的props上 changeInputValue(e){ const action={//1:创建action消息 type:'change_input_value', value:e.target.value,//把输入框里的值传给store }; dispatch(action);//2:把这个消息传给store处理 }, addItem(){ const action={ type:'add_item', }; dispatch(action); }, deleteItem(index){ const action={ type:'delete_item', index:index, }; dispatch(action); } } }; //目的:使TodoList和store做链接 export default connect(mapStateToProps,mapDispatchToProps)(TodoList);
3:store/index.js

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

export  default store;
4:store/reducer.js

const defaultState={//创建一个默认state
    inputValue:'',
    list:[],
};

export default (state=defaultState,action)=>{

    //3:处理store自动传过来的action消息
    if(action.type==='change_input_value'){
        const newState=JSON.parse(JSON.stringify(state));//对原有数据进行深拷贝、
        newState.inputValue=action.value;
        return newState;//4:reducer把newState传给store,store进行更新处理
    }
    if (action.type==='add_item'){
        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);//删除从索引开始的1个
        return newState;
    }



    return state;
}


你可能感兴趣的:(Redux)