【问题标题】:How to set default value in material-UI select box in react (after API call)?如何在 React 中的 Material-UI 选择框中设置默认值(在 API 调用之后)?
【发布时间】:2021-05-29 12:18:47
【问题描述】:

我尝试使用来自 MUI 的 Select Box 一切都很简单,就像MUI demo

只有一件事,我的默认值来自 API 调用之后。
所以,我需要“更新”默认值。
5 秒后,“年龄”的值更新为 30,但选择框没有。
如何解决?

    const [age, setAge] = React.useState<number>();
    
      React.useEffect(() => {
        //Emulate API call
        setTimeout(() => {
          setAge(30);
        }, 5000);
      }, []);
    
      const handleChange = (event: React.ChangeEvent<{ value: unknown }>) => {
        setAge(event.target.value as any);
      };
    
      return (
        <Box sx={{ minWidth: 120 }}>
          <FormControl fullWidth>
            <InputLabel id="demo-simple-select-label">Age</InputLabel>
            <Select
              labelId="demo-simple-select-label"
              id="demo-simple-select"
              value={age}
              label="Age"
              onChange={handleChange}
            >
              <MenuItem value={10}>Ten</MenuItem>
              <MenuItem value={20}>Twenty</MenuItem>
              <MenuItem value={30}>Thirty</MenuItem>
            </Select>
          </FormControl>
          Current Age: {age}
        </Box>
      );

沙盒代码:https://codesandbox.io/s/basicselect-material-demo-api-call-7k46b?file=/demo.tsx

【问题讨论】:

    标签: reactjs material-ui


    【解决方案1】:

    您只需要摆脱初始未定义的年龄值。 您可以在控制台中看到 undefined is out of the options range value 的错误。

    const [age, setAge] = React.useState<number | ''>('');
    

    【讨论】:

    • 是的,你是对的。只需要初始化值。 const [age, setAge] = React.useState&lt;number&gt;(0); 够了。
    猜你喜欢
    • 2022-10-13
    • 1970-01-01
    • 2019-01-08
    • 2019-02-10
    • 1970-01-01
    • 2018-08-09
    • 2013-08-25
    • 2021-11-26
    • 2020-10-25
    相关资源
    最近更新 更多