reactjs - 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
解决方案
你需要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]);
推荐阅读
- haskell - 是否可以使用 optparse-generic 同时拥有位置和命名 CLI 选项?
- javascript - 修复 d3 包布局中一个气泡的位置
- python - Python:选择在 vscode 命令面板中找不到的解释器命令
- android - OpenGL ES 2 投影切换前景和背景
- php - 当 PHP 请求 API 失败时如何处理错误
- c - 选择数组中的某些元素以创建新数组
- angular - 角度监听网络调用的开始和完成(下载功能)以显示进度条或微调器
- prolog - 为 n 位创建所有组合时出现意外的重复结果
- python-3.x - 如何在不让我的电脑死机的情况下加载一堆图像进行深度学习
- symfony - Symfony 非规范化:递归非规范化不起作用