javascript - TypeError: Can't read property 'map' of undefined when component uploads a file in React
问题描述
React newb here. When props.submitClk === true (the green light that my upload button has been clicked and a file is sent from another component's form) , I'm trying to update state setList with a new technique object, but for now just, 'SomeObject'. I then get a "TypeError Can't read property 'map' of undefined" after click. I tried messing around with some conditionals, but no luck after a few hours of trying. Is this a async issue and the map is happening too soon? handleRemove works fine when I'm deleting objects. If I remove the function under the if statement, it will not throw an error on form submit. Also, the object is going to be larger, that it is why its currently nested this way. Thanks for any answers.
function SampleData(props) {
const [list, setList] = React.useState( [
{
closedguard: [
{
name: "Armbar",
link: "",
x: "X",
id: "1",
},
{
name: "Triangle",
link: "",
x: "X",
id: "2",
},
{
name: "Omaplata",
link: "",
x: "X",
id: "3",
},
] }
] );
if( props.submitClk === true) {
setList([...list, 'SomeObject'])
}
const handleRemove = (id) => {
const newList = list[0].closedguard.filter(move => move.id !== id);
setList([{ closedguard: newList }]);
};
return (
<div className="guard">
<ul className="techUl">
{" "}
Closed Guard
{list.map((pos) =>
pos.closedguard.map((move, id) => (
<li
key={id}
className="techLi"
>{move.name}
<span onClick={(id) => handleRemove(move.id)}> {move.x}</span>
</li>
))
)}
</ul>
</div>
);
}
解决方案
First without someObject
you'll face Too many re-renders. React limits the number of renders to prevent an infinite loop.
Then you're updating nested object:
[
{
closedguard: [
{
name: "Armbar",
link: "",
x: "X",
id: "1",
},
{
name: "Triangle",
link: "",
x: "X",
id: "2",
},
{
name: "Omaplata",
link: "",
x: "X",
id: "3",
},
]
}
]
array of object, then object closedguard
is inside which is an array.
So what you can do inside condition is
// think is the some objects
const newObject = [
{
name: "test1",
link: "",
x: "X",
id: "5"
},
{
name: "test2",
link: "",
x: "X",
id: "56"
}
];
setList([{ closedguard: [...list[0].closedguard, ...newObject] }]);
instead of
setList([...list, 'SomeObject'])
推荐阅读
- html - 为什么我的标题周围的间距不会消失?
- api - kind undefined 在这里是什么意思?我找不到此错误的任何解决方案
- python - 使用 FOR 循环使用 TensorFlow 初始化权重
- if-statement - 这个公式可以在 Google 表格中的 ARRAYFORMULA 中使用吗?
- here-api - 静态流量模式表不存在
- reactjs - Chrome 开发工具显示所有名为“State”的 useState 钩子
- ruby - 如果为假,则打破每次迭代,但在其他情况下返回真红宝石
- oracle - 在 Oracle Apex 中将 1 秒添加到最小日期
- java - Java FX 问题窗口管理器(单例)
- c# - 来自 NLog 的 Asp-net 信息包含在类库中