【问题标题】:Getting Uncaught TypeError: boxes.map is not a function获取未捕获的类型错误:boxes.map 不是函数
【发布时间】:2022-09-24 02:25:05
【问题描述】:

不知道我做错了什么,但是当我尝试在我的应用程序中检测人脸时,我收到以下错误消息

我究竟做错了什么? 见下面的代码

从\'react\'导入反应; 导入\'./FaceRecognition.css\';

const FaceRecognition = ({ imageUrl, boxes }) => {
  return (
    <div className=\'center ma\'>
      <div className=\'absolute mt2\'>
        <img id=\'inputimage\' alt=\'\' src={imageUrl} width=\'500px\' heigh=\'auto\' />
        {boxes.map((box, i) => {
          return (
            <div
              key={i}
              className=\'bounding-box\'
              style={{ top: box.topRow, right: box.rightCol, bottom: box.bottomRow, left: box.leftCol }}></div>
          );
        })}
      </div>
    </div>
  );
};

export default FaceRecognition;

    标签: reactjs clarifai


    【解决方案1】:

    boxes 可能不是数组。 console.log(boxes) 在您返回 JSX 之前查看实际是什么框

    【讨论】:

      【解决方案2】:

      让我们看一下下面的例子:

      const List = ({ items }) => {
        return (
          <div>{items.map(item => <p>{item}</p>)}</div>
        );
      }
      
      const Home = () => {
          [items, setItems] = useState();
          useEffect(() => {
              setItems(["first","second","etc"]);
          }, []);
          return (
              <div><List items={items} /></div>
          );
      };
      

      这将导致相同的错误,因为 items 在第一个实例中不是数组,它们没有被初始化:

      [items, setItems] = useState();
      

      在这种情况下,useState 接收一个参数作为初始状态。要修复此错误,您应该使用空数组初始化状态,以便使用 map 方法:

      [items, setItems] = useState([]);
      

      因此,在生命周期之后,它将在给定一个空数组的情况下呈现 List 组件,然后触发 map 方法。您还可以通过在未定义对象或未传递道具时提供默认参数来解决此问题。

      const List = ({ items = [] }) => {
        return (
          <div>{items.map(item => <p>{item}</p>)}</div>
        );
      }
      

      这样,即使不传递 item 属性,它也会有一个空数组。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-08-06
        • 1970-01-01
        • 1970-01-01
        • 2022-11-19
        • 2019-06-06
        • 2019-05-24
        • 2021-12-15
        相关资源
        最近更新 更多