You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React组件读取state的length报错:Cannot read properties of undefined

解决React中读取length时的Cannot read properties of undefined错误

问题原因

  1. 函数参数未传递:你定义的stringLengthCheck声明了要接收name参数,但调用时stringLengthCheck()没传值,导致函数内的name是undefined,访问undefined.length直接抛出错误。
  2. 初始值未做兜底:如果父组件传递的name初始值是undefined而非空字符串,直接访问name.length也会触发报错。
  3. 焦点状态逻辑颠倒:inputFocus和inputNotFocus里的setIsFocus值写反了,onFocus应该设为true,onBlur设为false,否则样式判断逻辑完全混乱。
  4. 冗余状态没必要:isString状态完全可以通过name的实时值直接推导,单独维护反而容易出现状态不同步问题。

修复后的完整代码

import React, { useState } from 'react'
import styled from 'styled-components';
import geryO from '../../resources/images/img/greyO.png'

const InputWrap = styled.div`
  align-items: center;
  -webkit-appearance: none;
  background: rgb(250, 250, 250);
  border: 1px solid rgb(219, 219, 219);
  border-radius: 3px;
 
  .inputInput {
    font-size: 16px;
    background: rgb(250, 250, 250);
    border: 0;
    flex: 1 0 auto;
    margin: 0;
    outline: none;
    overflow: hidden;
    padding: 9px 0 7px 8px;
    text-overflow: ellipsis;
    color: rgb(38, 38, 38);
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
  }

  .userIdCheckGreyO {
    display: ${props=>props.isFocus && props.hasContent ? 'flex':'none'};
    align-items: center;
    border: 0;
    box-sizing: border-box;
    flex: 0 0 auto;
    flex-direction: row;
    font: inherit;
    font-size: 100%;
    height: 100%;
    margin: 0;
    padding: 0;
    padding-right: 8px;
    position: relative;
    vertical-align: middle;
  }
`

function SignUpNameInput({name = '', setName}) {
  // 焦点状态
  const [isFocus, setIsFocus] = useState(false);

  // 修正焦点逻辑:聚焦时设为true,失焦设为false
  const handleFocus = () => {
    setIsFocus(true);
  }

  const handleBlur = () => {
    setIsFocus(false);
  }

  // 直接通过name推导是否有内容,无需额外维护状态
  const hasContent = name.length > 0;

  console.log('hasContent :', hasContent)

  return (
    <InputWrap isFocus={isFocus} hasContent={hasContent}>
      <label>
        <span>
          <input 
            onFocus={handleFocus} 
            onBlur={handleBlur} 
            className='inputInput' 
            value={name} 
            onChange={(e)=>{setName(e.target.value)}}
          />
        </span>
      </label>
      <div className='userIdCheckGreyO'>
        <span>
          <img src={geryO} alt='greyO' />
        </span>
      </div>
    </InputWrap>
  )
}

export default SignUpNameInput;

核心修改点

  • 给name加默认值:通过name = ''兜底,避免父组件初始值为undefined时访问length报错。
  • 纠正焦点逻辑:把聚焦/失焦时的状态值修正,确保和实际交互一致。
  • 删除冗余状态:移除isString和对应的检查函数,直接用name.length > 0判断内容是否存在,减少状态维护成本。
  • 语义化命名:把样式props里的isString改成hasContent,含义更清晰。

内容的提问来源于stack exchange,提问作者MontaKr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 09:50:33