猿问

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

我在 React Native 中有一个 book 对象,我想使用 useState React Hook 在我的组件中使用这个对象,但我收到一条错误消息,指出“错误:对象作为 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 比较陌生,有人可以解决这个问题吗?


人到中年有点甜
浏览 98回答 3
3回答

红糖糍粑

<Text>{bookData}</Text>bookData 是一个数组。您不能使用内置组件显示数组。做这样的事情:<View>&nbsp; &nbsp; <Button title="Get Sample Book" onPress={getSampleBookDataHandler} />&nbsp; &nbsp; {bookData.map((item) => (&nbsp; &nbsp; &nbsp; &nbsp; <Text>{item.title}</Text>&nbsp; &nbsp; &nbsp; ))}&nbsp; &nbsp;</View>

交互式爱情

由于它是一个对象数组,因此您应该遍历该数组,这map是一个选项,也可以添加一个选项key,以便 React 可以更有效地更新组件。所以在 BookComponent 的返回值中你可以有return (&nbsp; &nbsp; <View>&nbsp; &nbsp; &nbsp; <Button title="Get Sample Book" onPress={getSampleBookDataHandler} />&nbsp; &nbsp; &nbsp; {bookData.map((book) => <Text key={book.title}>{book.title}</Text>)}&nbsp; &nbsp; </View>&nbsp; );

绝地无双

getSampleBookDataHandler 数据应该是相同的对象格式,如 { pages:1, title:'xxyy'}import React, {useState} from 'react';import {Text, View, Button} from 'react-native';import getSampleBookData from './BookPresenter';const BookComponent = () => {&nbsp; const [bookData, setBookData] = useState([]);&nbsp; const getSampleBookDataHandler = () => {&nbsp; &nbsp; setBookData(getSampleBookData);&nbsp; };useState(() => {&nbsp; getSampleBookDataHandler();},[getSampleBookDataHandler])&nbsp; return (&nbsp; &nbsp; <View>&nbsp; &nbsp; &nbsp; <Button title="Get Sample Book" onPress={getSampleBookDataHandler} />&nbsp; &nbsp; &nbsp; {bookData && <Text>{bookData.title}</Text> }&nbsp; &nbsp; </View>&nbsp; );};export default BookComponent;
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答