14-blog-注册界面

160 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第14天,点击查看活动详情

回顾react-redux用来搭建项目的使用步骤。指路👉 react-redux,demo

项目主要核心:组件增强(状态,行为)

用户注册:输入获得到的数据 / 回显数据。即相互映射。

初始先将数据设置为静态不可改变,方便测试。在仓库reducer中初始化数据:

const iniState={
    //初始化数据
    email:'2333',
    username:'111',
    password:'123456',
}

当使用组件connect增强时:

const mapStateToProps = state =>({state.user})

image.png

所以state.user获取到的是reducer.js其中之一。默认找到的为userReducer中初始数据

image.png

所以将state.user展开,它里面包括email,username,password三个键值对。

使用mapStateToProps后这三个键值对就被映射到props中了。(我讲的真明白)

//数据,state只是一个笼统的代表,state指全部reducer仓库。
const mapStateToProps = state =>({...state.user})  //同时将状态映射到props中
//行为
const mapDispatchToProps = dispatch=>{
  return{
    
  }
}
//增强
export default connect(mapStateToProps,mapDispatchToProps)(Regist)

从方法名就可以看出来,toProps,是将状态和行为都映射到props中了。所以可以在render钩子函数中解构出props中的值:

  const {email,username,password} = this.props //获取三个传过来的键值对

下面: 当输入的时候使用onChange事件监听输入动作,获取到输入的内容。

注意:用户无法直接接触state,只可以通过action指令来间接改变state

增强行为的步骤:

  1. 监听事件onChange:
onChange={this.changeEmail}
  1. 写方法:
 changeEmail=(e)=>{
     this.props.onEmailChange:
  }
  1. 增强行为、派发行为:
//直接将方法传给props了。 
const mapDispatchToProps = dispatch=>{
    return{
     onEmailChange:(暴露`action`事件)
    }
}

只要在增强状态/行为中写数据/方法,就会被传给props中。打印props可以看见:

image.png

  1. 通过action指令找事件
action中👇
export const registUpdate = (key,value)=>{
    return {`type`:,payload:} (暴露reducer)
}
  1. 通过type中改变状态
 switch (action.type) {
     case:
      //改变state
     break;
 }

具体实现步骤:

监听完OnChange后调用方法,将输入的e.target.value传给从props中获取的email值,

 changeEmail=(e)=>{
 //从props中获取方法
      this.props.onEmailChange("email",e.target.value) //传key,value
  }

将方法定义在增强行为中:

const mapDispatchToProps = dispatch=>{
  return{
   // 接收key value
    onEmailChange:(key,value)=>dispatch(action.registUpdate(key,value)),
    //dispatch()直接将数据映射在action中,所以调用action的指令。
  }
}

再来,从action中寻找客户端派发的指令,进入到reducer中:

action.js
import * as constant from "../constant"

export const registUpdate = (key,value)=>{
    return {type:constant.USER_REGIST,key,value}
}

进入reducer中通过指定type执行switch语句:

const iniState={
    //初始化数据
    email:'2333@qq.com',
    username:'111',
    password:'123456',
}
const userReducer = (state=iniState,action)=>{
    switch (action.type) { //判断传过来的type
        case constant.USER_REGIST:
           const {key,value} = action //获取action携带的值
           return {...state,[key]:value} //更改值(此处为先解构再覆盖)
        default:
            break;
    }
    return state;
}

小节:

其实action只不过是中间可暴露的一个指令,真正去传递改变状态的还是type。

本节难点,理解增强状态与行为的含义:都是会将內部数据/行为挂载到props中的两个函数。

增强数据本质是直接获取到指定reducer中的state(源数据)

增强行为本质是通过action、type等一系列中间去改变reducer中state

即,改变完state,也会实时获取state,两者相辅相成。