我如何提供解决此 Material UI 警告的值?

How can I provide a value that resolves this Material UI warning?

我正在从后端 (Node.js) 获取 API 数据(类别名称)到前端 (React)。目前,我的目标是从 Material UI 填充一个 Select 组件。对于获取 API 数据,我在后端使用 Express 和 Request;前端的 Axios。 显然,它有效,Select 组件得到了正确的选项列表,但出现了这个控制台警告:

Material-UI: You have provided an out-of-range value `` for the select component. Consider providing a value that matches one of the available options or ''. The available values are animal, career, celebrity, dev, explicit, fashion, food, history, money, movie, music, political, religion, science, sport, travel.

这些参考值来自获取的 API 数据,但我不知道如何更正。欢迎任何帮助。这是我的代码:

export default function Home() {
  const classes = useStyles();
  const [list, setList] = useState([]);
  const [categoryName, setCategoryName] = useState([]);

  useEffect(() => {
    axios
      .get("/getCategories")
      .then((response) => {
        setList(response.data.categories);        
      })
      .catch((e) => {
        console.log(e.response.data);
      });
  }, []);

  const handleChange = (event) => {
    setCategoryName(event.target.value);    
  };

  return (
    <div className={classes.root}>      
      <FormControl>
        <InputLabel id="category-label">Category</InputLabel>
        <Select         
          labelId="category-label"
          id="category"
          value={categoryName}
          onChange={handleChange}
        >
          {list.map((item) => (
            <MenuItem key={item} value={item}>
              {item}
            </MenuItem>
          ))}
        </Select>
      </FormControl>
    </div>
  );
}

您应该将 categoryName 初始化为空字符串而不是 Array

像这样添加 defaultValue = "" <Select ... defaultValue="" >

更多细节请参考这篇github

一切都很好,但你只需要一些改变 之前

const [categoryName, setCategoryName] = useState([]);

之后

 const [categoryName, setCategoryName] = useState('');

不要使用 categoryName 默认值作为数组或名称(因为渲染后使用了 useEffect 运行。所以在 useEffect 之后未设置的第一次值调用您在类别列表中设置的值并检查如果该值存在于类别列表中,否则它将生成警告),警告意味着您在 select 中添加 value(value={categoryName}) ,这不是使用 defaultValue 选项的最佳方式,但无论如何您只需将您的 categoryName 值设置为空,您就可以了解 useEffect 及其工作原理 https://stackblitz.com/edit/react-hmdhsf?file=src/home.js