簡體   English   中英

如何通過循環遍歷對象來重構這個 setState?

[英]How can I refactor this setState by looping through the object?

我覺得這應該比我發現的要容易得多......

現在,我有這個代碼,它可以工作:

componentDidMount() {
    fetch(API_URL + `/interviews/general/${this.props.employeeId}`)
      .then((res) => {
        if (!res.ok) {
          throw new Error();
        }
        return res.json();
      })
      .then((result) => {
        this.setState({
          organization: result[0].organization,
          address: result[0].address,
          website: result[0].website,
          industry: result[0].industry,
          co_status: result[0].co_status,
          mission: result[0].mission,
          
        });
        console.log(result);
      })
      .catch((error) => {
        console.log(error);
      });
  }

問題是這實際上是我正在檢索的數據,然后在表單中顯示結果。 但這只是其中的一部分。 在這個對象中實際上有接近 50 個鍵值對。 我必須有辦法循環遍歷那個 setState,對嗎?

這就是“結果”的樣子,這就是我的 fetch 返回的內容:

[{…}]
0:
COBRA_admin: ""
address: "1914 Skillman St, Suite 110153, Dallas, TX 75206"
benefits_broker: ""
co_status: "Private"
created_at: "2020-09-29T01:54:48.000Z"
employee_id: 104
general_id: 24
headcount_consultants: 0
headcount_fulltime: 0
headcount_nonexempt: 0
headcount_parttime: 0
headcount_temp: 0
hrlead_email: ""
hrlead_name: ""
hrlead_phone: ""
hrlead_title: ""
industry: "HR Consulting"
locations: ""
locations_headcount: ""
mission: "TO go and do great things. "
organization: "People Performance Resources LLC"
pointofcontact_email: ""
pointofcontact_name: ""
pointofcontact_phone: ""
pointofcontact_title: ""
retirement_admin: ""
seniorlead_email: ""
seniorlead_name: ""
seniorlead_phone: ""
seniorlead_title: ""
updated_at: "2020-09-30T20:47:39.000Z"
website: "www.pprhr.com"

如果您想要所有密鑰,只需執行以下操作:

this.setState({...result[0]});

使用 map 函數循環數據並返回狀態變量中的值,該狀態變量將維護特定鍵的整個結果數組的值。

componentDidMount() {
    fetch(API_URL + `/interviews/general/${this.props.employeeId}`)
      .then((res) => {
        if (!res.ok) {
          throw new Error();
        }
        return res.json();
      })
      .then((result) => {
        this.setState({
          organizations: result.map(item => item.organization),
          addresses: result.map(item => item.address),
          websites: result.map(item => item.website),
          industries: result.map(item => item.industry),
          co_status: result.map(item => item.co_status),
          missions: result.map(item => item.mission),   
        });
        console.log(result);
      })
      .catch((error) => {
        console.log(error);
      });
  }

顯示數據

// pass missions as a prop
const App = ({ missions }) => { 
 return (
    <ul> {missions.map(mission => <li> {mission} </li>)} </ul>
 )
}

除了async/await 之外,您是否介意考慮解構語句,請查看偽代碼:

async componentDidMount() {
  try {
    let response = await fetch( <url> );
    if (!response.ok) {
      throw Error(response.statusText);
    }
    const {
      organization, address, website, industry, co_status, mission
    } = response.json(); // deconstruction

    this.setState((prevState) => ({
      ...prevState,
      organization,
      address,
      website,
      industry,
      co_status,
      mission
    }));
  } catch (error) {
    throw Error(error.message);
  }
}

然而,這些功能涵蓋了相同的功能,請注意這些陳述是不相等的。 請看一下以了解async/await 與 Promisses 的區別,關鍵字是堆棧跟蹤。

如果您正在尋找一些好的必須知道的基礎知識,請訪問:Kent C. Dodds 的JavaScript to Know for React

暫無
暫無

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

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