简体   繁体   中英

How to use React Hook useState with a custom entity object?

I have a book object in react native and I want to use this object in my component using useState react hook but I am getting an error saying that "Error: Objects are not valid as a React child (found: object with keys {pages, title}). If you meant to render a collection of children, use an array instead."

Here is my book class:

export class Book {
  pages: number;
  title: string;

  constructor(pages: number, title: string) {
    this.pages = pages;
    this.title = title;
  }
}

Here is my BookComponent class:

import React, {useState} from 'react';
import {Text, View, Button} from 'react-native';
import getSampleBookData from './BookPresenter';

const BookComponent = () => {
  const [bookData, setBookData] = useState([{pages: -1, title: 'Untitled'}]);

  const getSampleBookDataHandler = () => {
    const book = getSampleBookData();
    setBookData(book);
  };

  return (
    <View>
      <Button title="Get Sample Book" onPress={getSampleBookDataHandler} />
      <Text>{bookData}</Text>
    </View>
  );
};

export default BookComponent;

I am relatively new to React Native, can anyone please fix this?

<Text>{bookData}</Text>

bookData is an Array. You cannot display an array using a built-in component. Do something like this:

<View>
    <Button title="Get Sample Book" onPress={getSampleBookDataHandler} />
    {bookData.map((item) => (
        <Text>{item.title}</Text>
      ))}   
</View>

As @AngelSalazar said, but as it is an array of objects you should iterate through the array, map is an option also add a key so React can update the component more effectively. So in the return value of BookComponent you can have

return (
    <View>
      <Button title="Get Sample Book" onPress={getSampleBookDataHandler} />
      {bookData.map((book) => <Text key={book.title}>{book.title}</Text>)}
    </View>
  );

getSampleBookDataHandler data should be same object format like { pages:1, title:'xxyy'}

import React, {useState} from 'react';
import {Text, View, Button} from 'react-native';
import getSampleBookData from './BookPresenter';

const BookComponent = () => {
  const [bookData, setBookData] = useState([]);

  const getSampleBookDataHandler = () => {
    setBookData(getSampleBookData);
  };

useState(() => {
  getSampleBookDataHandler();
},[getSampleBookDataHandler])

  return (
    <View>
      <Button title="Get Sample Book" onPress={getSampleBookDataHandler} />
      {bookData && <Text>{bookData.title}</Text> }
    </View>
  );
};

export default BookComponent;

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