反应挂钩-无法读取未定义的属性映射

时间:2020-07-18 02:08:00

标签: react-hooks react-hook-form

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

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

1 个答案:

答案 0 :(得分:0)

那是因为res.data.lists是未定义的。您可以尝试这样的事情:

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