React使用hooks遇到的坑_state中的某几个属性数据变成了空字符

起点

使用了useReducer来代替了useState,因为要提交多个数据,使用useState需要声明很多变量,所以选择组件内部的redux_____useReducer

import React, {
    
     useState, useEffect, useReducer,  } from 'react';
let initialState = {
    
    
    name: "",
    idType: "",
    personId: "",
    tel: "",
    mobile: "",
    email: "",
}
const reducerFun = (state, init) => {
    
    
    let obj = {
    
    }
    obj[init.key] = init.value
    switch (init.type) {
    
    
        case "changeValue":
            return {
    
     ...state, ...obj };
        case "getDetails":
            return {
    
     ...state, ...init.obj }
        case "resetValue":
            return initialState;
        default:
            return state
    }
}
const FaultTolerantManage = () => {
    
    
	let {
    
     idType, name, personId, mobile, tel, email, } = state	
    useEffect(() => {
    
    
      //获取默认值 ...
    }, [])
  const updateInfoFun = () => {
    
    
        if (name === '') {
    
    
            message.warning("请输入名称")
            return false;
        }
        let namereg = "[^a-zA-Z\\u4e00-\\u9fa5]"
        if (!isValidInput(name, namereg)) {
    
    
            message.warning('名称只允许字母、中文!')
            return false
        }
        if (email === '') {
    
    
            message.warning("请输入email地址")
            return false;
        }
     }
     
	 return (
        <div>
        //类似这样讲每一个元素都进行了绑定  inputName是对数据赋值的方法
			<Input title="固定电话" placeholder="请输入" value={
    
    tel} onChange={
    
    (e) => {
    
    inputName('tel', e) }} />
			.....
			//绑定修改点击事件
			<button>修改</button>
		</div>
        )
  }

问题表现

我的name和email字段都是必填的,但是我将email字段值变成空,第一次点击提交是没问题的,显示email不允许为空,这时候我再次点击修改按钮,就会提示我name为空,其实我的name是有值的。
当打印的时候可以看到name确实没有值。
但是我打印state.name是有值的。

解决办法

在修改函数中再次解构赋值,获取name、email等一系列的最新值。

  const updateInfoFun = () => {
    
    
        let {
    
     idType, name, personId, mobile, tel, email, } = state
        if (name === '') {
    
    
            message.warning("请输入名称")
            return false;
        }
        let namereg = "[^a-zA-Z\\u4e00-\\u9fa5]"
        if (!isValidInput(name, namereg)) {
    
    
            message.warning('名称只允许字母、中文!')
            return false
        }
        if (email === '') {
    
    
            message.warning("请输入email地址")
            return false;
        }
     }

原因:可能是数据更新不及时造成的,最顶端的解构赋值拿到的值并不是最新的值,有可能是因为组件没有重新render导致没有接收到最新的属性值。

猜你喜欢

转载自blog.csdn.net/qq_43291759/article/details/124197789