无法读取register.js上未定义错误的属性“ map”

时间:2020-04-30 04:58:04

标签: javascript reactjs map-function

因此,我正在遵循开发完整堆栈MERN应用程序的教程,并且我完全按照指示进行了所有步骤(大多数)。在注册页面上提交表单时,这是我得到的错误:无法读取未定义的属性“ map”。下面是Register.js页面中的代码。

import React, { useContext, useState, useEffect } from 'react'
import { Link } from 'react-router-dom';
import AuthContext from '../../context/authContext/authContext'

const Register = (props) => {
  const { register, isAuthencated, error, clearErrors, setError } = useContext(AuthContext)
  useEffect(() => {
    if (isAuthencated) {
      props.history.push('/')
    }
  }, [isAuthencated, props.history])

  const [user, setUser] = useState({
    name: '',
    email: '',
    password: '',
    password2: ''
  })
  const { name, email, password, password2 } = user
  onchange = (e) => {
    setUser({ ...user, [e.target.name]: e.target.value })
    if (error !== null) {
      clearErrors()
    }
  }
  onsubmit = (e) => {
    e.preventDefault()
    if (password !== password2) {
      setError('Password does not match')
    } else {
      register({
        name,
        email,
        password
      })
    }
  }
  return (
    <div className="register">
      <h1>Sign Up</h1>
      <form >
        <input type="text" name="name" placeholder="Name" value={name} onChange={onchange} />
        <input type="email" name="email" placeholder="Email" value={email} onChange={onchange} />
        <input type="password" name="password" placeholder="Password" value={password} onChange={onchange} />
        <input type="password" name="password2" placeholder="Confirm Password" value={password2} onChange={onchange} required />
        <input type="submit" value="Sing Up" className="btn" />
      </form>
      <div className="question">
        {error !== null && error.map(err => <button className="danger" type="button"  >{err.msg} <span onClick={() => clearErrors()}>X</span></button>)}
        <p>Already have an accout? {" "} <Link to='/login'>Sign In </Link></p>
      </div>
    </div >
  )
}

export default Register

3 个答案:

答案 0 :(得分:0)

尝试以下路线。因为错误变量可能不是数组类型

{error !== null && !!error.length && error.map(err => <button className="danger" type="button"  >{err.msg} <span onClick={() => clearErrors()}>X</span></button>)}

或尝试其他方法:

   {error !== null &&  Array.isArray(error) && error.map(err => <button className="danger" type="button"  >{err.msg} <span onClick={() => clearErrors()}>X</span></button>)}

错误对象应为数组。否则地图功能将无法正常工作

答案 1 :(得分:0)

首先改变

{error !== null && error.map(err => ....)}

{error != null && error.map(err => ....)}

因此未定义的内容也将被覆盖。

还要确保error对象仅初始化为数组[]

答案 2 :(得分:0)

您可以像{error && !!error.length && error.map((e) => {e})

它检查是否存在错误并且错误的长度大于0并执行map。

但是请确保error是一个数组。