简体   繁体   中英

rendering data to react

Error: Objects are not valid as a React child (found: object with keys {title, first, last}). If you meant to render a collection of children, use an array instead.

getting 40 errors of this using this componentdidmount not sure what it means already tried looking it up

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

Search results component

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

Issue

The mapped employee.name is an object with the {title, first, last} properties.

Solution

Here I usually dump these destructured values into an array and join them.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM