REACTjs | Getting this on Selection of option TypeError: state.users is undefined

REACTjs | Getting this on Selection of option TypeError: state.users is undefined

我正在尝试 post 数据使用对我的数据库的反应但是当我 select 从 axios 获取的选项时我得到一个错误 state.users is indefined ,我还收到警告

警告:组件正在将受控输入更改为不受控。这可能是由于值从已定义变为未定义造成的,这不应该发生。

import React, { useState, useEffect, useRef } from "react";
import "../../node_modules/bootstrap/dist/css/bootstrap.min.css";
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";
import axios from "axios";
const CreateExercise = () => {
  const [state, setState] = useState({
    username: "",
    description: "",
    duration: 0,
    date: new Date(),
    users: [],
  });

  const onChangeUsername = (e) => {
    setState({
      username: e.target.value,
    });
  };
  const onChangeDescription = (e) => {
    setState({
      description: e.target.value,
    });};
  const onChangeDuration = (e) => {
    setState({
      duration: e.target.value,
    });};
  const onChangeDate = (date) => {
    setState({
      date: date,
    }); };

  console.log(reff.current)
  const onSubmit = (e) => {
    e.preventDefault();

    const exercise = {
      username: state.username,
      description: state.description,
      duration: state.duration,
      date: state.date,  };

    axios.post("http://localhost:8000/exercise/add", exercise).then((doc) => {
      console.log(doc.data); });};

  useEffect(() => {
    axios.get("http://localhost:8000/users").then((doc) => {
      if (doc.data.length > 0) {
        setState({
          users: doc.data.map((user) => user.username),
          username: doc.data[1].username,
        }); } }); },[]);
  return (
    <div className="container">
      <div className="row">
        <div className="col-md-6 offset-3">
          <h3 className="my-3 text-center">Create New Exercise Log</h3>
          <form onSubmit={onSubmit}> <div className="form-group">
              <label>Username: </label>
              <select required className="form-control" value={state.username}
                onChange={onChangeUsername} >
                {state.users.map(function (user) {
                  return ( <option key={user} value={user}>
                      {user}
                    </option>  );   })}  </select>
            </div>
            <div className="form-group">
              <label>Description: </label>
              <input
                type="text"  required  className="form-control" value={state.description}
     onChange={onChangeDescription}
                  />
            </div>
            <div className="form-group">
              <label>Duration (in minutes): </label>
              <input
                type="text"
                className="form-control"
                value={state.duration}
                onChange={onChangeDuration} />

            </div> <div className="form-group">
              <div>
                <label className="mr-3">Date: </label>
                <DatePicker selected={state.date} onChange={onChangeDate} />
              </div>
            </div> <hr />
            <div className="form-group text-center">
              <input
                type="submit"
                value="Create Exercise Log"
                className="btn btn-primary" /> </div> </form>  </div>
      </div></div> );};

export default CreateExercise;

在挂钩处更改状态不同于在以前的基于 class 的组件中更改,后者 setState({ myKey: Myvalue }) 会为您完成脏工作并且只会更新 myKey 属性。有了钩子,当你的状态是一个对象时就不会发生这种情况。这意味着所有其他密钥都将丢失,因此 undefined.

为了避免你可以传递一个函数给setState,它的参数是currentState,并且这样做:

 setState(prevState => ({
  ...prevState,
  myKey: myValue,
}))