如何将React Hook useState与自定义实体对象一起使用?

时间:2020-07-28 14:32:37

标签: javascript reactjs react-native react-hooks react-component

我在react native中有一个book对象,我想使用useState react钩子在我的组件中使用此对象,但是我收到一条错误消息,指出“错误:对象作为React子对象无效(找到:带有键的对象{pages,title})。如果要渲染子级集合,请改用数组。”

这是我的课本:

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

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

这是我的BookComponent类:

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;

我对React Native还是比较陌生,有人可以解决这个问题吗?

3 个答案:

答案 0 :(得分:0)

<Text>{bookData}</Text>

bookData是一个数组。您不能使用内置组件显示数组。 做这样的事情:

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

答案 1 :(得分:0)

正如@AngelSalazar所说,但是由于它是一个对象数组,因此您应该遍历该数组,因此map是一个选项,同时还添加了key,以便React可以更有效地更新组件。因此,在BookComponent的返回值中,您可以拥有

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

答案 2 :(得分:0)

getSampleBookDataHandler数据应为相同的对象格式,例如{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;