【问题标题】:ReactJs - Not able to map data to table rows and columnsReactJs - 无法将数据映射到表行和列
【发布时间】:2021-03-10 08:57:02
【问题描述】:

我有调用 api 的 json 数组 -

[{"sup_Id":6,"sup_ShortCode":"A"},{"sup_Id":7,"sup_ShortCode":"B"},{"sup_Id":8,"sup_ShortCode":"C"},{"sup_Id":1000,"sup_ShortCode":"D"}]

React 组件读取这个数组为 -

import React,{useEffect,useState} from 'react'
import axios from 'axios';
function AllSuppliers() {
    const [suppliers, setstate] = useState([])
    useEffect(() => {
        // GET request using axios inside useEffect React hook
        axios.get('http://localhost:62815/api/values/GetAllSuppliers')
            .then(x => setstate(x.data))
            .catch(error => {
                alert(error);
                
            });;
    }, []);
    return (
        <>
            <table style={{width: '50%'}}>
            <thead>
                <tr>
                <th>
                    Supplier Id
                </th>
                <th>
                    Supplier Name
                </th>
                
                </tr>
                </thead>
                
                {
                    suppliers.map((supplier)=>{
                        <tr>
                            <td>
                            {supplier.sup_Id}
                            </td>
                            <td>
                            {supplier.sup_ShortCode}
                            </td>
                        </tr>
                    })
                }
               
            </table>
        </>
    )
}

export default AllSuppliers

但我得到的输出为 -

Json 数组不会在表内绑定。可能是什么问题?

【问题讨论】:

  • 你能告诉我们控制台的结果吗? console.log(suppliers)
  • 在 useEffect() 中添加依赖。这可能会重新渲染您的组件

标签: javascript json reactjs axios


【解决方案1】:

return 不见了:

suppliers.map((supplier)=> {
    return <tr>
        <td>
        {supplier.sup_Id}
        </td>
        <td>
        {supplier.sup_ShortCode}
        </td>
    </tr>
})

【讨论】:

    【解决方案2】:

    修复应该是这样的:

                        suppliers.map((supplier)=>{
                        return(
                            <tr>
                                <td>
                                    {supplier.sup_Id}
                                </td>
                                <td>
                                     {supplier.sup_ShortCode}
                                </td>
                            </tr>
                            )
                    })
    

    如果这不能解决问题,那么它与数据的检索有关。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多