【问题标题】:TypeError: links.map is not a function ReactTypeError:links.map 不是 React 函数
【发布时间】:2020-09-11 08:46:34
【问题描述】:

我正在使用 reactjs 打字稿,在尝试显示来自服务器的 JSON 数据时似乎无法阻止此错误:

import React, { useRef, useState } from "react";
import useHttp from "../hooks/usehttp";

const HomePage: React.FC = () => {
const [links, setLinks] = useState([]);
const ref = useRef<HTMLInputElement>(null);
const { request } = useHttp();

const pressHandler = async (event: React.KeyboardEvent) => {
if (event.key === "Enter") {
  try {
    const data = await request(
      "http://localhost:5000/api/link/generate-guest",
      "POST",
      { from: ref.current!.value },
      {}
    );
    alert(data.message);
    console.log(data.link.to); // the link => localhost:5000/jshdadsa
    setLinks(data.link.to);
    console.log(links); // shows undefined ?????
  } catch (error) {
    alert(error);
  }
}
};

return (
<>
  <div className="row">
    <div className="col s8 offset-s2" style={{ paddingTop: "2rem" }}>
      <div className="input-field">
        <input
          placeholder="Enter link"
          id="link"
          type="text"
          ref={ref}
          onKeyPress={pressHandler}
        />
        <label htmlFor="link">Enter link</label>
      </div>
      <div>
        { {links.map((link: any) => {
          return (
            <ul className="collection with-header">
              <li className="collection-item">{link}</li>
            </ul>
          );
        })} }
      </div>
    </div>
  </div>
</>
);
};

export default HomePage;

不知道我错过了什么。

【问题讨论】:

  • data.link.to 的输出是什么?是数组吗?
  • @AhedKabalan 它是字符串“localhost:5000/jshdadsa”。

标签: json reactjs typescript


【解决方案1】:

使用此代码来更新示例中的链接数组:

setLinks([...links, data.link.to])

【讨论】:

    猜你喜欢
    • 2016-09-02
    • 2018-12-23
    • 2023-03-27
    • 2021-07-20
    • 2016-11-21
    • 2020-12-04
    • 2021-07-11
    • 2015-09-01
    • 2015-08-22
    相关资源
    最近更新 更多