【问题标题】:React JSON is undefinedReact JSON 未定义
【发布时间】:2021-06-26 21:57:31
【问题描述】:

我正在从 API 获取这个 JSON:

{
  "data": {
    "email": "test@tre.com",
    "inserted_at": "2021-03-30T15:37:06",
    "links": [
      {
        "id": 1,
        "title": "My link title",
        "url": "http://google.com"
      },
      {
        "id": 2,
        "title": "My Youube title",
        "url": "http://youtube.com"
      }
    ]
  }
}

我正在使用 Hooks 以这种方式获取它:

export default function Notes() {
  const [json, setJSON] = useState([]);

  useEffect(() => {
    fetch("http://localhost:4000/api/users/1", {
      method: "GET"
    })
      .then((response) => response.json())
      .then((json) => {
        // console.log(data);
        setJSON(json);
      })
      .catch((err) => {
        console.error(err);
      });
  }, [setJSON]);

然后我尝试像这样展示它:

return (
    <>
      <div className="content">
          {JSON.stringify(json)}
          <h1>{json.email}</h1>
</div>
</>
);

{JSON.stringify(json)} 行显示 JSON。

但是&lt;h1&gt;{json.email}&lt;/h1&gt; 行没有显示任何内容。

我不知道为什么会发生这种情况以及如何访问我的变量。

谢谢。感谢您的帮助

【问题讨论】:

  • 错字:你忘记了结构的data. 部分。
  • 是的,但是它说 json.data 未定义。我不知道为什么。我输入了 json.data.email
  • 这能回答你的问题吗? Reactjs async rendering of components 虽然它使用类组件,但问题/解决方案是相同的。获取是异步的,因此 data 在可用之前是未定义的,因此您必须在使用数据之前处理该状态(加载)。
  • 试试 {json &&

    {json.email}

    }
  • 不是真的(:我没有使用 Ajax

标签: json reactjs react-hooks undefined


【解决方案1】:
<h1>{json.data && json.data.email}</h1>

而不是

<h1>{json.email}</h1>

【讨论】:

    【解决方案2】:

    数据是数组形式还是对象形式?

    您将初始状态定义为数组 ad,因此您不能这样做

    // you can't do json.email if you expect the response as and array
    
    
     const [json, setJSON] = useState([]);
    

    改成

     const [json, setJSON] = useState({});
    

    如果它是一个对象。然后在模板中做

    {json.data && <h1>{json.data.email}</h1>}
    

    【讨论】:

    • 根据问题中的数据,可能更接近json.data.email,并且我不会用对象(也不是数组)来初始化状态,否则条件就变得没用了。只需useState() 就足以阻止渲染,直到接收到数据。
    • 是的,你是对的。我错了。但我仍然收到 json.data 未定义。我完全迷路了
    • emile.bergeron,你明白了。伙计们谢谢。我怎样才能给你解决?
    • 是的,接受这个答案就可以了;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 2018-08-01
    • 2018-12-20
    • 2020-10-16
    • 2017-03-30
    • 2020-03-16
    • 1970-01-01
    相关资源
    最近更新 更多