簡體   English   中英

ReactJS & Javascript: Getting “Error: Objects are not valid as a React child” when trying to set JSON Objects into a state hook

[英]ReactJS & Javascript: Getting “Error: Objects are not valid as a React child” when trying to set JSON Objects into a state hook

概述:我有兩個組件:ComponentA 和 ComponentB,我想向我的 API 發出 POST 請求,並將返回的 JSON 字符串存儲到 useState 掛鈎中,然后將該 Z9ED39E2EA931586B732EF5B64E 傳遞給組件。 在 ComponentB 中,我想使用 the.map() function 來遍歷道具的內容。

API 響應 JSON 數據結構: [{object: 1, name: 'bob'},{object: 2, name: 'joe'}...]

這是我的 state 鈎子定義:

const [data, setData] = useState([]);

我的 API 電話:

  const handleSubmit = () => {
    console.log("Function Called");
    fetch("/post", {
      method: "POST",
      mode: "cors",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(formik.values),
    })
      .then((response) => response.json())
      .then((res) => {
        console.log(typeof res);
        setData(res);
      })
      .catch((err) => {
        console.log(err);
      });
  };

和我的 ComponentB.map() function

      <tbody>
        {props.responses.length > 0 ? (
          props.responses.map((response) => (
            <tr
              class={
                tableRow === "" ? (tableRow = "table-primary") : (tableRow = "")
              }
            >
              <td>{response.object}</td>
              <td>{response.name}</td>
            </tr>
          ))
        ) : (
          <tr></tr>
        )}
      </tbody>

每當我撥打 API 電話時,我都會收到此錯誤:

Error: Objects are not valid as a React child (found: object with keys {object, name}). If you meant to render a collection of children, use an array instead.

是否可以將 state 中的響應設置為 JSON object 並將其傳遞給 ComponentB? 如果是這樣,我做錯了什么?

或者我是否需要將其作為字符串傳遞,然后在 ComponentB 中傳遞 JSON.parse()? (唯一的問題是JS拋出了cors錯誤,這是為什么呢?

錯誤告訴您您嘗試將整個 JS object 放入 JSX 標記中,您不能這樣做。 看看你從 API 得到什么,以及你如何嘗試顯示它。

我最終將組件 B 移動到組件 A 中。我認為原因是當瀏覽器從后端請求數據時,瀏覽器希望將數據保留在其域內,因此當它從瀏覽器到組件 B,該組件 B 位於虛擬 DOM 中,尚未在瀏覽器中呈現。 所以不是組件交互拋出的錯誤,而是瀏覽器和ReactJS服務器的交互拋出的錯誤。 go 關於這個的方法不是傳遞整個state,而是傳遞單個道具。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM