typescript 使用选择组件从数组中返回对象

wkyowqbh  于 2022-12-24  发布在  TypeScript
关注(0)|答案(1)|浏览(155)

我想返回列表中一个项目的整个对象表示,但是,当进行选择并调用handleChangeSelectAuto时,将返回useState中的原始值,并且从那里开始,始终返回先前选择的值。
如何从列表中选择项目并返回其所有关联数据?

import React, { useEffect, useState } from 'react';
import { FormControl, InputLabel, Select, MenuItem } from '@mui/material';

interface AutoSelectorProps {}

const AutoSelector: React.FC<AutoSelectorProps> = () => {
  const [auto, setAuto] = useState({} as object);
  const [autoName, setAutoName] = useState('' as string);

  const [autoList, setAutoList] = useState([
    {
      id: 1,
      name: 'Car',
      color: 'red'
    },
    {
      id: 2,
      name: 'Truck',
      color: 'blue'
    },
  ]);

  const handleChangeSelectAuto = async (value: string) => {
    const index = autoList.findIndex((item) => {
      return item.name === value;
    });

    setAutoName(value);
    setAuto(autoList[index]);

    console.log(auto);
    // 1st log: {}
    // 2nd log: object from previous selection
    // 3rd log: object from previous selection, etc.
  };

  return (
    <div>
      <FormControl>
        <InputLabel>Select Auto</InputLabel>
        <Select
          value={autoName}
          label="Auto"
          onChange={(e) => handleChangeSelectAuto(e.target.value as string)}
        >
          {autoList.map((item) => {
            return (
              <MenuItem key={item.name} value={item.name}>
                {item.name}
              </MenuItem>
            );
          })}
        </Select>
      </FormControl>
    </div>
  );
};

export default AutoSelector;

P.S.如果我添加一个按钮和处理程序来记录auto,它将返回正确的值,但我没有看到竞争条件。

y4ekin9u

y4ekin9u1#

useState是异步的。它不会立即显示值。请使用useEffect查看更新后的值

useEffect(() => {
       console.log(auto);

}, [auto])

相关问题