【问题标题】:What's the cause of this error, TypeError: Cannot read properties of undefined (reading 'toString')这个错误的原因是什么,TypeError: Cannot read properties of undefined (reading 'toString')
【发布时间】:2022-07-12 04:07:53
【问题描述】:

我正在尝试创建一个搜索功能,我正在关注https://www.freecodecamp.org/news/how-to-react-components/ 中的代码请注意,我使用的是我自己的“API”,而不是 freecodecamp 使用的那个。但是我收到一条错误消息:无法读取未定义的属性(读取“toString”)这可能是什么原因

这是我的代码,它是相同的,唯一的区别是获取 URL。

import React from 'react'
import { useEffect } from 'react';
import { useState } from 'react';
function Main() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
const [query, setQuery] = useState("");
const data = Object.values(items);
const search_parameters = Object.keys(Object.assign({}, ...data));
// const search_parameters = ["title", ...data]
function search(data) {
    return items.filter(
      (item) =>
        search_parameters.some((parameter) =>//Error here
          item[parameter].toString().toLowerCase().includes(query)
        )
    );
  }
useEffect(() => {
    fetch('http://localhost:3005/movies')
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <>
      <input
          type="search"
          name="search-form"
          id="search-form"
          className="search-input"
          placeholder="Search for..."
          onChange={(e) => setQuery(e.target.value)}
        />
        <div className='card-wrapper'>
        {search(data).map((item)=>(
            <div className="movie-card">
            <p className="title">{item.title}</p> <br></br>
            <img src={item.cover} className="card-img"/> <br></br>
        </div>
        ))}
        </div>
      </>
    );
  }

 }

export default Main

【问题讨论】:

    标签: javascript reactjs json


    【解决方案1】:

    大概有问题:

    item[parameter].toString().toLowerCase().includes(query)
    

    item 对象上没有名为 parameter 的属性(应命名为 property),因此 undefined 没有 toString() 方法。要解决此问题,您应该先检查此类属性是否存在。

    ...
    if (parameter in item) {
      return item[parameter].toString()
        .toLowerCase()
        .includes(query);
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 2021-11-10
      • 2021-11-03
      • 2021-11-08
      • 2021-11-25
      • 2022-08-10
      • 2022-01-16
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多