[英]React/Codesandbox, mapping over array results in .map is not a function
I'm working on a small react project, and I'm trying to map over an array, and display the names (in react).我正在做一个小型反应项目,我正在尝试在一个数组上 map,并显示名称(在反应中)。
I've been trying to find a solution to this error (.map is not a function), and the only suggestion I found was adding the index as a key.我一直在尝试找到解决此错误的方法(.map 不是函数),我发现的唯一建议是将索引添加为键。 It doesn't seem to be solving it, any help would be greatly appreciated!它似乎没有解决它,任何帮助将不胜感激!
Your groups is not an array hence the.map is not a part of the groups.您的组不是数组,因此.map 不是组的一部分。 I tried your code sandbox and the groups is having following value.我尝试了您的代码沙箱,并且这些组具有以下价值。
3 people should be one group!
Check how is your groups being set.检查您的组是如何设置的。
for the workaround until you fix your group value you can do something like this.对于解决方法,直到你修复你的组值,你可以做这样的事情。
import React, { useState } from "react";
import { shuffleArray, createGroups } from "./utils";
import "./styles.css";
//TODO groups should be at least 3 people
//MAYBE also add option people per group
const App = () => {
const [names, setNames] = useState("");
const [numGroup, setNumGroup] = useState(2);
const handleNames = (e) => {
e.preventDefault();
};
const shuffledArr = shuffleArray(names.split(" "));
const groups = createGroups(numGroup, shuffledArr);
return (
<div className="App">
<h1>Coffee Groups</h1>
<form className="form" onSubmit={handleNames}>
<textarea
name="listOfNames"
type="text"
value={names}
onChange={(e) => setNames(e.target.value)}
/>
<div className="button">
<label>groups</label>
<input
min="2"
className="numInput"
type="number"
value={numGroup}
onChange={(e) => setNumGroup(e.target.value)}
/>
<button type="submit" onClick={() => console.log(groups)}>
Run
</button>
</div>
</form>
<div>
{Array.isArray(groups) && groups.map((group, idx) => {
return (
<ul key={idx}>
<li>Group {idx + 1}</li>
{group.map((person, idx) => {
return <li key={idx}>{person}</li>;
})}
</ul>
);
})}
</div>
</div>
);
};
export default App;
On codesandbox, if you hover over line 16 const groups = createGroups(numGroup, shuffledArr);
在代码沙盒上,如果您在第 16 行上使用 hover const groups = createGroups(numGroup, shuffledArr);
you'll see that groups is any[] |你会看到 groups 是 any[] | "3 people should be one group". “3人应为一组”。 Since in some cases groups is not an array, line 43 JS complains that.map() does not exist on a string.由于在某些情况下组不是数组,第 43 行 JS 抱怨 .map() 不存在于字符串上。
You can fix this by making createGroups only returning an array, and then instead of groups?您可以通过让 createGroups 只返回一个数组而不是组来解决这个问题? try groups.length >= 3?
尝试groups.length >= 3?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.