簡體   English   中英

渲染數據以做出反應

[英]rendering data to react

錯誤:對象作為 React 子對象無效(發現:object 鍵為 {title, first, last})。 如果您打算渲染一組子項,請改用數組。

使用此組件得到 40 個錯誤didmount 不確定這意味着什么已經嘗試查找

class Search extends Component {
  state = {
  results: [],
  search: "",
};
componentDidMount() {
API.getRandomUsers()
// console.log(API.getRandomUsers())
.then(res => this.setState({ results: res.data.results }))
.catch(err => console.log(err));
};

render() {
return (
<div>
  <Navbar />
  <Form />
  <Wrapper>
  <Table>
  <thead>
    <tr>
      <th>Image</th>
      <th>Name</th>
      <th>Phone</th>
      <th>Email</th>
      <th>DOB</th>
    </tr>
  </thead>
  <tbody>
    <SearchResults
     results = {this.state.results} />
  </tbody>
</Table>
  </Wrapper>
</div>
)}

搜索結果組件

const SearchResults = (props) => {
  console.log(props)
  return (
<tr>
{props.results.map((employee, index) => {
  return (
    <tr key={index}>
      <img alt={employee.results} className="img-fluid" src={props.src} />
      <td> {employee.name} </td>
      <td> {employee.phone} </td>
      <td> {employee.email} </td>
      <td> {employee.dob} </td>
  </tr>
)})}

問題

映射的employee.name是一個具有{title, first, last}屬性的object。

解決方案

在這里,我通常將這些解構的值轉儲到一個數組中並加入它們。

{props.results.map((employee, index) => {
  const {
    dob,
    email,
    name: {title, first, last},
    phone,
  } = employee;

  return (
    <tr key={index}>
      <img alt={employee.results} className="img-fluid" src={props.src} />
      <td>{[title, first, last].join(' ')}</td>
      <td>{phone}</td>
      <td>{email}</td>
      <td>{dob}</td>
  </tr>
)})}

暫無
暫無

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

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