簡體   English   中英

通過 function 調用 Map() 不返回 JSX

[英]Map() not returning JSX when called through a function

我正在嘗試 output 一堆 li,同時遍歷 map function。 問題是代碼直接放在渲染返回語句中時有效,但如果我將其組織在幫助程序 function 中並在返回語句中調用 function 時,該代碼將停止工作。

作品:

const UserList = (props) => {
  if(props.items.length === 0){
    return (
      <div className="center">
        <h2>No users found.</h2>
      </div>
    );
  }
}

return <ul className="users-list">
  {
    props.items.map(user => {
      console.log(user.name);
      return <li>{user.id}</li>   
    })
  }
</ul>

不工作:

const UserList = (props) => {
  if(props.items.length === 0){
    return (
      <div className="center">
        <h2>No users found.</h2>
      </div>
    );
  }
}

const renderList = () => {
  props.items.map(user => {
    console.log(user.name);
    return <li>{user.id}</li>   
  })
};

return <ul className="users-list">
  {renderList()}
</ul>

您需要在您的方法上有 return 聲明。

const { items } = props; 

const renderList = () => {
  return items.map(user => {
      return <li>{user.id}</li>   
    }
  )
};

或者代碼更少的簡短版本。 在箭頭函數中,如果只返回結果而不進行進一步處理,則不需要寫下花括號和return語句。

const { items } = props; 

const renderList = () => items.map(user => <li>{user.id}</li>);

做這個:

const renderList = () => {
    return props.items.map(user => {
        console.log(user.name);
        return <li>{user.id}</li>   
      }
    )
};

暫無
暫無

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

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