尝试在React中创建动态表格,出现奇怪的错误。

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

Trying to create dynamic tables in React, getting bizarre error

问题

以下是代码的翻译部分:

import React from "react";
import ReactDOM from "react-dom";
import { useState } from "react";
import "./style.css";

function Trains() {
  const [trainsList, setTrainsList] = useState([
    { name: "Thomas", destination: "Boston" },
    { name: "Duncan", destination: "New York" },
  ]);

  return (
    <div>
      <table>
        <thead>name</thead>
        <thead>destination</thead>

        {trainsList.map((train) => (
          <tbody key={train.name}>
            <td>{train.name}</td>
            <td>{train.destination}</td>
          </tbody>
        ))}
      </table>
      <br />
      Train Name: <input type="text" id="trainName" />
      <br />
      Destination: <input type="text" id="trainDest" />
      <br />
      <button
        onClick={() =>
          setTrainsList((prev) =>
            prev.push({ name: "Dennis", destination: "Denville" })
          )
        }
      >
        Submit
      </button>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Trains />);

请注意,翻译的文本是在代码中的引号中,所以无需进行额外的翻译。如果您有其他问题或需要进一步的帮助,请告诉我。

英文:

So, I'm trying to create a simple program in react. The state is an array of objects. It prints these objects into a table. Standard table construction (<tr>, <th>, <td>) etc. works fine for the initial render, but when I try to re-render I get bizarre errors I'm trying to adapt to. So, this is my code so far.

import React from &quot;react&quot;;
import ReactDOM from &quot;react-dom&quot;;
import { useState } from &quot;react&quot;;
import &quot;./style.css&quot;;
function Trains() {
const [trainsList, setTrainsList] = useState([
{ name: &quot;Thomas&quot;, destination: &quot;Boston&quot; },
{ name: &quot;Duncan&quot;, destination: &quot;New York&quot; },
]);
return (
&lt;div&gt;
&lt;table&gt;
&lt;thead&gt;name&lt;/thead&gt;
&lt;thead&gt;destination&lt;/thead&gt;
{trainsList.map((train) =&gt; (
&lt;tbody key={train.name}&gt;
&lt;td&gt;{train.name}&lt;/td&gt;
&lt;td&gt;{train.destination}&lt;/td&gt;
&lt;/tbody&gt;
))}
&lt;/table&gt;
&lt;br /&gt;
Train Name: &lt;input type=&quot;text&quot; id=&quot;trainName&quot; /&gt;
&lt;br /&gt;
Destination: &lt;input type=&quot;text&quot; id=&quot;trainDest&quot; /&gt;
&lt;br /&gt;
&lt;button
onClick={() =&gt;
setTrainsList((prev) =&gt;
prev.push({ name: &quot;Dennis&quot;, destination: &quot;Denville&quot; })
)
}
&gt;
Submit
&lt;/button&gt;
&lt;/div&gt;
);
}
const root = ReactDOM.createRoot(document.getElementById(&quot;root&quot;));
root.render(&lt;Trains /&gt;);

But even changing the table lingo like that still isn't enough. I get these bizarre errors:

bundle.js:7294 Warning: validateDOMNesting(...): Text nodes cannot appear as a child of &lt;thead&gt;.
at thead
at table
at div
at Trains (http://localhost:3000/static/js/bundle.js:32:86)

And

bundle.js:7294 Warning: validateDOMNesting(...): &lt;td&gt; cannot appear as a child of &lt;tbody&gt;.
at td
at tbody
at table
at div
at Trains (http://localhost:3000/static/js/bundle.js:32:86)

How on Earth can I create a table or use "thead" to any effect if I can't even put any text in the headings or put tds in my table rows? How the heck do I make tables in react?

答案1

得分: 1

表格行

您可能打算使您的表格看起来像这样:

<table>
  <thead>
    <tr>
      <th>name</th>
      <th>destination</th>
    </tr>
  </thead>

  <tbody>
    {trainsList.map((train) => (
      <tr key={index}>
        <td>{train.name}</td>
        <td>{train.destination}</td>
      </tr>
    ))}
  </tbody>
</table>

请注意在标题和正文中创建表格行的<tr>元素。

map中的key

另外,请注意在<tr>元素中的key属性。尽管使用数组的索引作为键不是一个好的做法,但使用一个可能会重复的名称要好得多。

修复setState

最后,单击按钮后更新状态的函数可以重写为:

<button
  onClick={() => 
    setTrainsList((prev) => {
      return [
        ...prev,
        { name: "Dennis", destination: "Denville" },
      ];
    })
  }
>
  提交
</button>
英文:

Table Rows

You've probably intended to make your table look something like that:

&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;name&lt;/th&gt;
&lt;th&gt;destination&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
{trainsList.map((train) =&gt; (
&lt;tr key={index}&gt;
&lt;td&gt;{train.name}&lt;/td&gt;
&lt;td&gt;{train.destination}&lt;/td&gt;
&lt;/tr&gt;
))}
&lt;/tbody&gt;
&lt;/table&gt;

Note the &lt;tr&gt; elements to create a table rows both in the header and in the body.

Key in a map

Also, note the key attribute in the &lt;tr&gt; element. It is not a good practice to use an index of an array as a key, although it is much better that using a name that can be repeated.

Fix setState

Finally, the function to update state after clicking a button can be rewritten to that:

&lt;button
onClick={() =&gt;
setTrainsList((prev) =&gt; {
return [
...prev,
{ name: &quot;Dennis&quot;, destination: &quot;Denville&quot; },
];
})
}
&gt;
Submit
&lt;/button&gt;

答案2

得分: 0

代码部分已经被排除,以下是翻译好的部分:

错误出现在“Submit”按钮中的“setTrainsList”方法中。push方法返回数组的新长度,但不会改变原始数组。相反,你应该使用concat方法或展开语法来在React中向数组添加新元素:

<button onClick={() =>
  setTrainsList((prev) => [...prev, { name: "Dennis", destination: "your butt" }])
}>
  Submit
</button>

这应该解决错误,并在点击按钮时向火车列表添加一个新元素。

英文:

The error is in the setTrainsList method defined in the Submit button. The push method returns the new length of the array, but does not change the original array. Instead, you must use the concat method or the spread syntax to add a new element to an array in React:

&lt;button onClick={() =&gt;
setTrainsList((prev) =&gt; [...prev, { name: &quot;Dennis&quot;, destination: &quot;your butt&quot; }])
}
&gt;
Submit
&lt;/button&gt;

This should resolve the error and add a new element to the train list when you click the button.

huangapple
  • 本文由 发表于 2023年2月14日 07:07:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75442010.html
匿名

发表评论

匿名网友

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

确定