如何使 1 号线正常工作?
饼干
function GetBrandData() {
var jsonData = "";
useEffect(() => {
async function getData5() {
const response = await fetch(variables.API_URL);
jsonData = await response.json();
alert(JSON.stringify({ jsonData }));
/* The line above shows the following output
{
"jsonData": [{ "id": 1, "name": "ASUS", "isSelected": false },
{ "id": 2, "name": "DELL", "isSelected": true },
{ "id": 3, "name": "HP", "isSelected": true },
{ "id": 4, "name": "Lenovo", "isSelected": false },
{ "id": 5, "name": "MSI", "isSelected": false }]
}
*/
}
getData5();
}, [])
return (jsonData);
}
<>
var listBrands = GetBrandData();
// LINE #1
{listBrands.map(brand => <div>{<input key={brand.id} type='checkbox' value= {brand.name} onChange={handleCpusCheckbox} />}{brand.name}</div>)};
</>
我正在尝试循环来自数据库的思想对象。
我也尝试过一些网上找到的方法。但 还是不行。
您的代码有一些不正确的地方。
你的代码应该看起来像这样。
const MyComponent = () => {
const [listBrands, setListBrands] = useState();
const [loading, setLoading] = useState(true);
async function getData5() {
const response = await fetch(variables.API_URL);
jsonData = await response.json();
alert(JSON.stringify({ jsonData }));
setListBrands(jsonData);
setLoading(false);
/* The line above shows the following output
{
"jsonData": [{ "id": 1, "name": "ASUS", "isSelected": false },
{ "id": 2, "name": "DELL", "isSelected": true },
{ "id": 3, "name": "HP", "isSelected": true },
{ "id": 4, "name": "Lenovo", "isSelected": false },
{ "id": 5, "name": "MSI", "isSelected": false }]
}
*/
}
useEffect(() => {
getData5();
}, [])
if (loading) {
return <div>Loading...</div>;
}
// LINE #1
return {listBrands.map(brand => <div>{<input key={brand.id} type='checkbox' value= {brand.name} onChange={handleCpusCheckbox} />}{brand.name}</div>)};
</>
}
这里 useEffect 在组件安装时运行,它运行函数
getData5
并在函数内部将数据设置为 listBrands,这会触发组件的重新渲染,这次您将获得数据,并且映射组件将按预期工作。