簡體   English   中英

為什么這個 React 代碼在它是一個數組但適用於單個對象時無法訪問

[英]Why is This React Code Unreachable When Its an Array But Works for a Single Object

嗨,我想使用 map 函數來迭代我的數據並在 React 中填充一個表。 使用 State 我將我的變量設置為一個空數組,但是當我來映射它時,代碼無法訪問,我不知道為什么。

注意:如果我在構造函數中映射一個單獨的對象,它可以完美地工作。

更新

解決了! _ 對不起,伙計們 - 我的錯誤 - 我錯過了第二次render() {這顯然導致代碼無法訪問

Eriks 解決方案有效,但 Get 請求仍未觸發 - 我知道這是一個單獨的問題......

我們如何清理這篇文章? 我是新來的?

這是因為 map 函數中的 return 和 render 沒有返回任何內容。

import { Container, Table } from "react-bootstrap"
import RestClient from "../../common/RestClient"
import AppUrl from "../../common/AppUrl"

export class ViewAllSubbies extends Component {
  constructor() {
    super()
    this.state = {
      subbieData: []
    }
  }

  componentDidMount() {
    RestClient.GetRequest(AppUrl.AllSubbies).then(result => {
      this.setState({ subbieData: result })
    })
  }

  render() {

    const Subbies = this.state.subbieData;
    return (Subbies.map(item=> {
      return (<tr>
        <td>{item.id}</td>
        <td>{item.contractor_name}</td>
        <td>{item.contractor_type}</td>
        <td>{item.contractor_email}o</td>
        <td>{item.contractor_phone_number}</td>
      </tr>)
    }))
  } 

請參考更新后的代碼。

那是因為您已經為數組“Subbies”和地圖項“Subbies”賦予了相同的名稱,只需為地圖項賦予不同的名稱,例如“Subby”或其他名稱。 並且這些值應該是地圖項的值,如下所示:

const Subbies = this.state.subbieData;
const SubbieTable = Subbies.map(subby=> {
  return
  <tr>
    <td>{subby.id}</td>
    <td>{subby.contractor_name}</td>
    <td>{subby.contractor_type}</td>
    <td>{subby.contractor_email}o</td>
    <td>{subby.contractor_phone_number}</td>
  </tr>
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM