渲染数据以做出反应

时间:2021-02-04 05:43:48

标签: javascript json reactjs

错误:对象作为 React 子对象无效(找到:带有键 {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>
)})}

1 个答案:

答案 0 :(得分:0)

问题

映射的 employee.name 是一个具有 {title, first, last} 属性的对象。

解决方案

这里我通常将这些解构的值转储到一个数组中并加入它们。

{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>
)})}