【问题标题】:React hooks - cannot read property map of undefined反应钩子 - 无法读取未定义的属性映射
【发布时间】:2020-07-18 02:08:00
【问题描述】:

这是我的列表组件。我正在尝试通过列表数组进行映射,但它显示“无法读取未定义的属性映射”的错误消息

import { Link } from 'react-router-dom'
import axios from 'axios'
import apiUrl from './../../apiConfig'
const Lists = (props) => {
  const [lists, setLists] = useState([])
  useEffect(() => {
    axios({
      url: `${apiUrl}/lists`,
      method: 'GET',
      headers: {
        'Authorization': `Token token=${props.user.token}`
      }
    })
      .then(res => setLists(res.data.lists))
      .catch(console.error)
  }, [])
  // const listsJsx = lists.map(list => (
  //   <li key={list._id}>
  //     <Link to={`/lists/${list._id}`}>{list.name}</Link>
  //   </li>
  // ))
  return (
    <div>
      <h4>Lists</h4>
      <ul>
        {lists && lists.length > 0
          ? lists.map(list => {
            return <div key={list._id}><Link to={`/lists/${list._id}`}>{list.name}</Link></div>
          })
          : 'Loading...'}
      </ul>
    </div>
  )
}
export default Lists

【问题讨论】:

    标签: react-hooks react-hook-form


    【解决方案1】:

    那是因为 res.data.lists 是未定义的。你可以试试这样的:

    .then(res => setLists(res.data.lists ? res.data.lists || []))
    

    【讨论】:

    • 感谢您的建议。我们发现问题实际上来自我们的后端 API Route ,我们没有将列表写成复数形式。
    猜你喜欢
    • 2023-03-13
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多