首页 > 解决方案 > How to properly display a Material UI Native select and change the selection using a state hook

问题描述

Code SandBox Here https://codesandbox.io/s/wild-brook-jpeio?file=/src/App.js

I acquire an array of values using useEffect hook. The array variable is set using useState hook

The value and onChange attributes of Native Select also uses another state variable and its set function to update it.

Using the below part of code to use the set function to set the selected value of the Native Select just after the useEffect gets the data.

 // set the default selection on first load
  if (!isEmpty(combolist)) {
    console.log(combolist[0].name);
    setSelection(combolist[0].name);
  }

But this is giving too many renders error.

How to fix this and achieve my objective

标签: reactjsreact-hooksmaterial-ui

解决方案


你需要useEffect像这样使用一个钩子:


  useEffect(() => {
    if (data.length) {
      const combolist = data.map((obj) => pick(obj, ["id", "name"]));

      // set the default selection on first load
      if (!isEmpty(combolist)) {
        console.log(combolist[0].name);
        setSelection(combolist[0].name);
      }
    }
  }, [data]);

推荐阅读