Reactjs React hooks includes()用于检查数组中是否存在值,每次都给出一个错误答案
我有一个简单的电话簿,它应该检查姓名是否存在于“person”数组中。我使用person.map和includes()。有人能解释为什么这个代码给出一次“false”,而值应该是“true”,即人名数组中存在人名吗?它每次都这样做,但只有一次Reactjs React hooks includes()用于检查数组中是否存在值,每次都给出一个错误答案,reactjs,react-hooks,Reactjs,React Hooks,我有一个简单的电话簿,它应该检查姓名是否存在于“person”数组中。我使用person.map和includes()。有人能解释为什么这个代码给出一次“false”,而值应该是“true”,即人名数组中存在人名吗?它每次都这样做,但只有一次 //获取一个钩子函数 const{useState}=React; 常量应用=()=>{ const[person,setPerson]=useState([{name:“johndoe”}]); const[newName,setName]=useSt
//获取一个钩子函数
const{useState}=React;
常量应用=()=>{
const[person,setPerson]=useState([{name:“johndoe”}]);
const[newName,setName]=useState(“”);
const addName=(事件)=>{
event.preventDefault();
const nameObject={name:newName};
让mapped=person.map((ele)=>ele.name);
let found=mapped.includes(newName);
log(“找到了吗?”,找到了);
};
常量handleNameChange=(事件)=>{
setName(event.target.value);
};
返回(
名称
添加
);
};
ReactDOM.render(
,
document.getElementById(“根”)
)
当您要将项添加到数组并更改状态时,必须使用以下方法之一:
setPerson(person => person.concat(nameObject)) with .concat()
setPerson(person => [...person, nameObject]) with … spread
人物数组始终为空。您永远不会在其中推送新值,因此当然包含函数,它将始终返回false。(我使用的是TS,很抱歉这个示例)
从“react”导入{useState}
常量应用=()=>{
const[person,setPerson]=useState([{name:'johndoe'}])
const[newName,setName]=useState(“”)
const addName=(事件:任意)=>{
event.preventDefault()
常量nameObject={name:newName}
让mapped=person.map((ele:any)=>ele.name)
let found=mapped.includes(newName)
如果(找到){
返回//
}
setPerson([…person,nameObject])
}
常量handleNameChange=(事件:React.ChangeEvent)=>{
setName(event.target.value)
}
报税表(
名称
添加
)
}
导出默认应用程序;
问题已解决。当我更新person数组并清空newName时,在“”中有一个空格。因此,相同的名字在开头有一个空格,是“不同的名字”
我建议使用
some
array函数,这将避免事件的双重迭代found=person。一些(p=>p.name==newName)
与问题无关,但您不需要使用map
和includes
方法来搜索person
数组;您可以使用find
或findIndex
方法来完成。如果我在您的输入框中键入John Doe
,控制台将打印找到它了吗?正确
。这里有什么问题?我遗漏了setPerson等,因为这不是问题所在。使用some和find时也会出现同样的现象(我可以添加一个曾经存在的名称)。
import { useState } from "react"
const App = () => {
const [person, setPerson] = useState<any>([{name: 'John Doe'} ])
const [newName, setName] = useState<any>('')
const addName = (event: any) => {
event.preventDefault()
const nameObject = {name: newName}
let mapped = person.map((ele: any) => ele.name)
let found = mapped.includes(newName)
if(found){
return //
}
setPerson([...person, nameObject])
}
const handleNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
setName(event.target.value)
}
return (
<form onSubmit={addName}>
<div>
name
<input
value ={newName}
onChange={handleNameChange} />
</div>
<div>
<button type='submit'>add</button>
</div>
</form>
)
}
export default App;
if (found) {
console.log('found the name')
}
else {
console.log('new name')
setPerson(person.concat(nameObject))
}
setName(' ')