简体   繁体   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

Overview: I have two components: ComponentA and ComponentB, I would like to make a POST request to my API and store the returned JSON string into a useState hook, and then pass that state to componentB.概述:我有两个组件:ComponentA 和 ComponentB,我想向我的 API 发出 POST 请求,并将返回的 JSON 字符串存储到 useState 挂钩中,然后将该 Z9ED39E2EA931586B732EF5B64E 传递给组件。 In ComponentB I would like to use the.map() function to iterate through the prop's contents.在 ComponentB 中,我想使用 the.map() function 来遍历道具的内容。

API response JSON Data Structure: [{object: 1, name: 'bob'},{object: 2, name: 'joe'}...] API 响应 JSON 数据结构: [{object: 1, name: 'bob'},{object: 2, name: 'joe'}...]

Here is my state hook definition:这是我的 state 钩子定义:

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

My API call:我的 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);
      });
  };

and my ComponentB.map() function和我的 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>

whenever I make the API call I get this error:每当我拨打 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.

is it possible to set the response in the state as a JSON object and pass it to ComponentB?是否可以将 state 中的响应设置为 JSON object 并将其传递给 ComponentB? If so what am I doing wrong?如果是这样,我做错了什么?

Or do I need to pass it off as a string and then JSON.parse() in ComponentB?或者我是否需要将其作为字符串传递,然后在 ComponentB 中传递 JSON.parse()? (the only problem with this is that JS throws a cors error, why is that? (唯一的问题是JS抛出了cors错误,这是为什么呢?

Error tell you that you try to put whole JS object in JSX markup, you can't do that.错误告诉您您尝试将整个 JS object 放入 JSX 标记中,您不能这样做。 Just look what you getting from API and how you trying to display it.看看你从 API 得到什么,以及你如何尝试显示它。

I ended up moving component B inside Component A. The reason, I believe is that when the browser requested data from the backend, the browser wants to keep the data within its domain, so it throws a cors error when it passes the data from the browser to Component B which would be inside the virtual DOM, not yet rendered in the browser.我最终将组件 B 移动到组件 A 中。我认为原因是当浏览器从后端请求数据时,浏览器希望将数据保留在其域内,因此当它从浏览器到组件 B,该组件 B 位于虚拟 DOM 中,尚未在浏览器中呈现。 So it's not an error thrown by the interaction of the components but by the interaction of the browser and the ReactJS server.所以不是组件交互抛出的错误,而是浏览器和ReactJS服务器的交互抛出的错误。 The way to go about this is not to pass the entire state, but instead to pass individual props. go 关于这个的方法不是传递整个state,而是传递单个道具。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM