Uncaught runtime errors : 对象不适用作 React 子元素

huangapple go评论97阅读模式
英文:

Uncaught runtime errors : Objects are not valid as a React child

问题

我已经理解您的要求,以下是您提供的文本的翻译:

我面临了这个问题已经有两天了,我不知道如何获取数据。我检查了它的类型是 scheme,它显示为对象。我使用了 Object.keys 方法,但仍然得到相同的错误。
这是我的数据结构的图片。这里只显示了两个,但可能会有更多,paymentData 是一个数组。请告诉我如何做到这一点。

[schemeAPIslice 文件]

export const schemeApiSlice = apiSlice.injectEndpoints({
    endpoints: (builder) => ({
        getSchemeOfUser: builder.query({
            query: () => ({
                url: `${SCHEME_API_URL}`,
                method: "GET",
                credentials: "include",
            }),
            keepUnusedDataFor: 5,
            providesTags: ["Schemes"],
        }),
        createScheme: builder.mutation({
            query: (data) => ({
                url: `${SCHEME_API_URL}/scheme_started`,
                method: "POST",
                body: data,
                credentials: "include",
            }),
            invalidatesTags: ["Schemes"],
        }),
    }),
});

export const { useGetSchemeOfUserQuery, useCreateSchemeMutation } = schemeApiSlice;

[Dashboard.js]

const { data } = useGetSchemeOfUserQuery();
<div className='container'>
    <SchemeData schemes={data?.schemes} />
</div>

[schemedata 组件]

const SchemeData = ({ schemes }) => {
    console.log(schemes);
    console.log(typeof schemes);

    console.log(typeof JSON.stringify(schemes));

    return (
        <div>
            <h5>Scheme List</h5>
            <ul>
                {Object.keys(schemes).map((item, i) => (
                    <li className='py-5' key={i}>
                        <span>{schemes[item]}</span>
                    </li>
                ))}
            </ul>
        </div>
    );
};

<details>
<summary>英文:</summary>

I am facing this issue for 2 days now I cant&#39;t get it how to can fetch the data. I check= the type of it is scheme it is showing object.  I used Object.keys method but still geting the same error.
here is image of my data structure. Here is only showing two but can be more and the paymentData is an array. Please tell me how can i do this.

[![enter image description here][1]][1]

schemeAPIslice file
-------------------

    export const schemeApiSlice = apiSlice.injectEndpoints({
    	endpoints: (builder) =&gt; ({
    		getSchemeOfUser: builder.query({
    			query: () =&gt; ({
    				url: `${SCHEME_API_URL}`,
    				method: &quot;GET&quot;,
    				credentials: &quot;include&quot;,
    			}),
    			keepUnusedDataFor: 5,
    			providesTags: [&quot;Schemes&quot;],
    		}),
    		createScheme: builder.mutation({
    			query: (data) =&gt; ({
    				url: `${SCHEME_API_URL}/scheme_started`,
    				method: &quot;POST&quot;,
    				body: data,
    				credentials: &quot;include&quot;,
    			}),
    			invalidatesTags: [&quot;Schemes&quot;],
    		}),
    	}),
    });
    
    export const { useGetSchemeOfUserQuery, useCreateSchemeMutation } = schemeApiSlice;

Dashboard.js
------------

    const { data } = useGetSchemeOfUserQuery();
    &lt;div className=&#39;container&#39;&gt;
    				&lt;SchemeData schemes={data?.schemes} /&gt;
    			&lt;/div&gt;

schemedata component
--------------------

    const SchemeData = ({ schemes }) =&gt; {
    	console.log(schemes);
    	console.log(typeof schemes);
    
    	console.log(typeof JSON.stringify(schemes));
    
    	return (
    		&lt;div&gt;
    			&lt;h5&gt;Scheme List&lt;/h5&gt;
    			&lt;ul&gt;
    				{Object.keys(schemes).map((item, i) =&gt; (
    					&lt;li className=&#39;py-5&#39; key={i}&gt;
    						&lt;span&gt;{schemes[item]}&lt;/span&gt;
    					&lt;/li&gt;
    				))}
    			&lt;/ul&gt;
    		&lt;/div&gt;
    	);
    };

  [1]: https://i.stack.imgur.com/WOGFy.png

</details>


# 答案1
**得分**: 1

The only significant issue with the code is that `schemes` is an array of objects and the code is trying to render the raw element objects directly.

这段代码唯一的重要问题是`schemes`是一个对象数组,代码试图直接渲染原始元素对象。

This is functionally equivalent to mapping the `schemes` array directly (`Object.keys(schemes)` is just an array of the array indices):

这在功能上等同于直接映射`schemes`数组(`Object.keys(schemes)`只是一个数组的索引数组):

Since `item` is still an object you will need to pick out the properties you want to actually render. For example, `item.user` or `item.wallet`.

因为`item`仍然是一个对象,所以你需要选择要实际渲染的属性。例如,`item.user`或`item.wallet`。

If you are wanting to render the `item.paymentData` this is yet again another array of objects, each array element needs to be mapped to valid JSX. For example, a list of monthly payments.

如果你想渲染`item.paymentData`,那么这又是另一个对象数组,需要将每个数组元素映射到有效的JSX。例如,一个月度支付列表。

If the `schemes` prop value is sometimes undefined then you can either provide a fallback prop value:

如果`schemes`属性值有时是未定义的,那么你可以提供一个备用的属性值:

Or pass a fallback value to `SchemeData`:

或者将一个备用值传递给`SchemeData`:

<details>
<summary>英文:</summary>

The only significant issue with the code is that `schemes` is an array of objects and the code is trying to render the raw element objects directly.

```jsx
{Object.keys(schemes).map((item, i) =&gt; (
  &lt;li className=&#39;py-5&#39; key={i}&gt;
    &lt;span&gt;{schemes[item]}&lt;/span&gt; // &lt;-- schemes[item] is object!
  &lt;/li&gt;
))}

This is functionally equivalent to mapping the schemes array directly (Object.keys(schemes) is just an array of the array indices):

{schemes.map((item, i) =&gt; (
  &lt;li className=&#39;py-5&#39; key={i}&gt;
    &lt;span&gt;{item}&lt;/span&gt; // &lt;-- item is object!
  &lt;/li&gt;
))}

Since item is still an object you will need to pick out the properties you want to actually render. For example, item.user or item.wallet.

Example:

{schemes.map((item, i) =&gt; (
  &lt;li className=&#39;py-5&#39; key={i}&gt;
    &lt;div&gt;User: {item.user}&lt;/div&gt;
    &lt;span&gt;Wallet: {item.wallet}&lt;/span&gt;
  &lt;/li&gt;
))}

If you are wanting to render the item.paymentData this is yet again another array of objects, each array element needs to be mapped to valid JSX. For example, a list of monthly payments.

&lt;ul&gt;
  {schemes.map((item) =&gt; (
    &lt;li className=&#39;py-5&#39; key={item._id}&gt;
      &lt;div&gt;User: {item.user}&lt;/div&gt;
      &lt;span&gt;Wallet: {item.wallet}&lt;/span&gt;
      &lt;ul&gt;
        &lt;p&gt;Payments&lt;/p&gt;
        {item.paymentData.map(({ amount, month_name }, i) =&gt; (
          &lt;li key={i}&gt;{month_name} - {amount}&lt;/li&gt;
        ))}
      &lt;/ul&gt;
    &lt;/li&gt;
  ))}
&lt;/ul&gt;

If the schemes prop value is sometimes undefined then you can either provide a fallback prop value:

const SchemeData = ({ schemes = [] }) =&gt; {
  return (
    &lt;div&gt;
      &lt;h5&gt;Scheme List&lt;/h5&gt;
      &lt;ul&gt;
        ...
      &lt;/ul&gt;
    &lt;/div&gt;
  );
};

Or pass a fallback value to SchemeData:

&lt;SchemeData schemes={data?.schemes ?? []} /&gt;

huangapple
  • 本文由 发表于 2023年6月8日 13:17:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76428799.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定