我如何设置数组 useState() 反应的默认值

时间:2021-04-05 12:03:25

标签: javascript html reactjs

我从后端 API 获取对象列表数组我的任务是在下拉选项中设置值的第一个索引以将其设置为默认查看图像我需要设置第一个用户名代替用户

const [userL, setUserL] = useState([]);
  useEffect(() => {
    axios
      .get(`${DJANGO_SERVER_ADDRESS}/auth/analyst/`)
      .then((res) => {
        setUserL(res.data);
      })
      .then(
        (result) => {
        },
        (error) => {
        }
      );
  }, []);
const handleSelectChangeL = (object, action) => {
    setIndex(userL[object.id]);
    setUserlevel(null);
    console.log("select check", object.label, action.name, index);
    let name = action.name;
    let value = object.value;

    setFormData((prevFormData) => ({
      ...prevFormData,
      [name]: value,
    }));
  };
           <Col lg={2}>
              <label for="user">
                <header>User</header>
              </label>
              <Select
                options={userL.map((data, index) => ({
                  value: data.username,
                  label: data.username,
                  id: index,
                }))}
                styles={styles2}
                value={user}
                name="user"
                onChange={handleSelectChangeL}
                placeholder="User"
                theme={(theme) => ({
                  ...theme,
                  colors: {
                    ...theme.colors,
                    text: "black",
                    primary25: "#d6fdf7",
                    primary: "#0bb7a7",
                    primary50: "#d6fdf7",
                  },
                })}
              ></Select>
            </Col>

see an image I need to set here that first user name

1 个答案:

答案 0 :(得分:0)

你在 useState 中传递的参数是默认值。您可以传递一个非空数组:

const [userL, setUserL] = useState(['Default first value']);