如何在React中循环数据库对象?

问题描述 投票:0回答:1

如何使 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>)};  
</>

我正在尝试循环来自数据库的思想对象。

我也尝试过一些网上找到的方法。但 还是不行。

reactjs dictionary object
1个回答
0
投票

您的代码有一些不正确的地方。

  1. useEffect 不应该位于任何函数内,它应该位于组件的顶层。阅读这个
  2. 如果您没有任何正在更改的状态,则组件仅在安装时渲染一次,在代码中 listBrands 不会在获取数据时使组件重新渲染,因为您没有将其用作状态。

你的代码应该看起来像这样。

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,这会触发组件的重新渲染,这次您将获得数据,并且映射组件将按预期工作。

© www.soinside.com 2019 - 2024. All rights reserved.