问题描述
我正在做一个小型反应项目,我正在尝试映射一个数组,并显示名称(在反应中)。
我一直试图找到解决此错误的方法(.map 不是函数),我发现的唯一建议是将索引添加为键。它似乎没有解决它,任何帮助将不胜感激!
解决方法
您的组不是数组,因此 .map 不是组的一部分。我尝试了您的代码沙箱,并且这些组具有以下值。
3 people should be one group!
检查您的群组是如何设置的。
在您修复组值之前的解决方法,您可以执行以下操作。
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;
,
在代码和框上,如果您将鼠标悬停在第 16 行 const groups = createGroups(numGroup,shuffledArr);
上,您会看到组是 any[] | “3人为一组”。由于在某些情况下组不是数组,第 43 行 JS 抱怨 .map() 不存在于字符串中。
您可以通过让 createGroups 只返回一个数组而不是组来解决这个问题吗?试试groups.length >= 3?