为什么我的 Array find 函数无法正常工作,即使我做了同样的事情 document

Why my Array find function doesn't work properly even I did the same thing document

所以我的代码有问题,但我不明白哪里错了..所以基本上我想找到我在我的帐户中注册的项目.. 基本上就是这样的代码。

const evergreens = [
  { name: "cedar", count: 2 },
  { name: "fir", count: 6 },
  { name: "pine", count: 3 }
];

// suppose we need to skip the first element
const result = evergreens.find((tree, i) => {
  if (tree.count > 1 && i !== 0) return true;
});

这就是我在这篇文章中看到的 link

当我试图在后端获取我的数据时它不起作用..这是代码..

const [name,setname] = useState()
  const [password,setpassword] = useState()
  const [key,setkey] = useState()
  
  const [option,setoption] = useState("Register")

  const [list,setlist] = useState([])

  useEffect(() => {
      axios.get('http://localhost:7171/users/')
        .then(list => setlist(list.data))
        .catch(err => console.log(err))
        // console.log(list)
  },[])

  const handleSubmit = e => {
    
    e.preventDefault()

    const Inputs = {key:key, name:name, password:password}

    if (option == "Register") {
      console.log(list)

      // this shows the list of the data []

      const findItem = list.find((data,i) => 
        data.name === name
      )
      //but this one doesn't work I don't understand how I just did the same thing though..

      console.log(findItem)
      //This one will gives an undefined value

      // Register(Inputs)
      
      setname("")
      
      setpassword("")
      
      setkey("")

    }
  
  }

有没有我在这里没有应用的东西,或者我的代码是否有错误?我相信我没有在这里跳过任何东西。我不明白它是如何显示未定义值的。

已编辑

(2) [{…}, {…}] 0: {_id: '6232ac00ae5cf39abb58febd', name: 'Hahahatdog', password: '123123123', key: 'ABCDEFGHIJKLMNOP', createdAt: '2022-03-17T03:33:20.809Z', …} 1: {_id: '6232ac14ae5cf39abb58fec0', name: 'cutekabatdog', password: '123123123', key: 'nakoiyakKLMNOP', createdAt: '2022-03-17T03:33:40.339Z', …} length: 2 [[Prototype]]: Array(0)

根据共享的代码 here,问题似乎来自输入字段未正确更新状态。您的代码是:

<input
  type="text"
  className="form-group-input"
  name="name"
  onChange={(e) => setname(e)}
/>

这导致在状态中分配事件 (e) 本身,而不是在 e.target.value 中分配值。所以这样做应该可以解决您的问题。此外,我建议添加 value={name} 作为输入的道具以控制输入,从而在您提交表单时将其清除。这将导致:

<input
  type="text"
  className="form-group-input"
  name="name"
  onChange={(e) => setname(e.target.value)}
  value={name}
/>

您可以阅读更多关于 React 中受控组件的信息 here