В моем приложении, ориентированном на реакцию, я получаю ошибку вызова API исключения компонента: «Текстовые строки должны отображаться в <Text />»

Это приложение, ориентированное на реакцию, работает без ошибок, когда API не вызывается, ошибки возникают только при запуске API, созданного с помощью NodeJs. Я получаю сообщение об ошибке как ошибка вызова API Текстовые строки должны отображаться внутри компонента.

Ниже приведена ошибка, отображаемая в консоли, где я запускаю приложение для реагирования.

Api call error

Error: Text strings must be rendered within a <Text> component.

This error is located at:
    in RCTView (at View.js:34)
    in View (at ProductContainer.js:125)
    in RCTView (at View.js:34)
    in View (at ScrollView.js:1124)
    in RCTScrollView (at ScrollView.js:1260)
    in ScrollView (at ScrollView.js:1286)
    in ScrollView (at ProductContainer.js:124)
    in RCTView (at View.js:34)
    in View (at Container.js:12)
    in Container (at connectStyle.js:392)
    in Styled(Container) (at ProductContainer.js:104)
    in ProductContainer (at SceneView.tsx:122)
    in StaticContainer
    in StaticContainer (at SceneView.tsx:115)
    in EnsureSingleNavigator (at SceneView.tsx:114)
    in SceneView (at useDescriptors.tsx:153)
    in RCTView (at View.js:34)
    in View (at CardContainer.tsx:245)
    in RCTView (at View.js:34)
    in View (at CardContainer.tsx:244)
    in RCTView (at View.js:34)
    in View (at CardSheet.tsx:33)
    in ForwardRef(CardSheet) (at Card.tsx:573)
    in RCTView (at View.js:34)
    in View (at createAnimatedComponent.js:165)
    in AnimatedComponent (at createAnimatedComponent.js:215)
    in ForwardRef(AnimatedComponentWrapper) (at Card.tsx:555)
    in PanGestureHandler (at GestureHandlerNative.tsx:13)

at node_modules\react-native\Libraries\LogBox\LogBox.js:148:8 in registerError
at node_modules\react-native\Libraries\LogBox\LogBox.js:59:8 in errorImpl
at node_modules\react-native\Libraries\LogBox\LogBox.js:33:4 in console.error
at node_modules\expo\build\environment\react-native-logs.fx.js:27:4 in error
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:104:6 in reportException
at node_modules\react-native\Libraries\Core\ExceptionsManager.js:171:19 in handleException
at node_modules\react-native\Libraries\Core\ReactFiberErrorDialog.js:43:2 in showErrorDialog
at node_modules\react-native\Libraries\Renderer\implementations\ReactNativeRenderer-dev.js:15258:32 in logCapturedError

at [native code]:null in dispatchAction
at Screens\Products\ProductContainer.js:44:10 in axios.get.then$argument_0
at node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
at node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:181:14 in _callImmediatesPass
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:441:30 in callImmediates
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:387:6 in __callImmediates
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 in __guard$argument_0        
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 in flushedQueue
at [native code]:null in flushedQueue
at [native code]:null in callFunctionReturnFlushedQueue

Вот скриншот ошибки, отображаемой в мобильном приложении В моем приложении, ориентированном на реакцию, я получаю ошибку вызова API исключения компонента: «Текстовые строки должны отображаться в &lt;Text /&gt;»

И код, показанный в ошибке,

if (!hostContext.isInAParentText) {

    throw Error("Text strings must be rendered within a <Text> component.");
  }

Ниже представлен код ProductContainer.js.

import React, { useState, useCallback } from "react";
import {
  View,
  StyleSheet,
  ActivityIndicator,
  FlatList,
  ScrollView,
  Dimensions,
} from "react-native";
import { Container, Header, Icon, Item, Input, Text } from "native-base";
import { useFocusEffect } from "@react-navigation/native";
import axios from "axios";

import ProductList from "./ProductList";
import SearchedProduct from "./SearchedProducts";
import Banner from "../../Shared/Banner";
import CategoryFilter from "./CategoryFilter";
import baseURL from "../../assets/common/baseUrl";

var { height } = Dimensions.get("window");

const ProductContainer = (props) => {
  const [products, setProducts] = useState([]);
  const [productsFiltered, setProductsFiltered] = useState([]);
  const [focus, setFocus] = useState();
  const [categories, setCategories] = useState([]);
  const [productsCtg, setProductsCtg] = useState([]);
  const [active, setActive] = useState();
  const [initialState, setInitialState] = useState([]);
  const [loading, setLoading] = useState(true);

  useFocusEffect(
    useCallback(() => {
      setFocus(false);
      setActive(-1);

      // Products
      axios
        .get(`${baseURL}products`)
        .then((res) => {
          setProducts(res.data);
          setProductsFiltered(res.data);
          setProductsCtg(res.data);
          setInitialState(res.data);
          setLoading(false);
        })
        .catch((error) => {
          console.info("Api call error");
        });

      // Categories
      axios
        .get(`${baseURL}categories`)
        .then((res) => {
          setCategories(res.data);
        })
        .catch((error) => {
          console.info("Api call error");
        });

      return () => {
        setProducts([]);
        setProductsFiltered([]);
        setFocus();
        setCategories([]);
        setActive();
        setInitialState();
      };
    }, [])
  );

  // Product Methods
  const searchProduct = (text) => {
    setProductsFiltered(
      products.filter((i) => i.name.toLowerCase().includes(text.toLowerCase()))
    );
  };

  const openList = () => {
    setFocus(true);
  };

  const onBlur = () => {
    setFocus(false);
  };

  // Categories
  const changeCtg = (ctg) => {
    {
      ctg === "all"
        ? [setProductsCtg(initialState), setActive(true)]
        : [
            setProductsCtg(
              products.filter((i) => i.category._id === ctg),
              setActive(true)
            ),
          ];
    }
  };

  return (
    <>
      {loading == false ? (
        <Container>
          <Header searchBar rounded>
            <Item>
              <Icon name = "ios-search" />
              <Input
                placeholder = "Search"
                onFocus = {openList}
                onChangeText = {(text) => searchProduct(text)}
              />
              {focus == true ? (
                <Icon onPress = {onBlur} name = "ios-close" />
              ) : null}
            </Item>
          </Header>
          {focus == true ? (
            <SearchedProduct
              navigation = {props.navigation}
              productsFiltered = {productsFiltered}
            />
          ) : (
            <ScrollView>
              <View>
                for the banner of the home page
                <View>
                  <Banner />
                </View>
                <View>
                  <CategoryFilter
                    categories = {categories}
                    categoryFilter = {changeCtg}
                    productsCtg = {productsCtg}
                    active = {active}
                    setActive = {setActive}
                  />
                </View>
                {productsCtg.length > 0 ? (
                  <View style = {styles.listContainer}>
                    {productsCtg.map((item) => {
                      return (
                        <ProductList
                          navigation = {props.navigation}
                          key = {item.name}
                          item = {item}
                        />
                      );
                    })}
                  </View>
                ) : (
                  <View style = {[styles.center, { height: height / 2 }]}>
                    <Text>No products found</Text>
                  </View>
                )}
              </View>
            </ScrollView>
          )}
        </Container>
      ) : (
        // Loading
        <Container style = {[styles.center, { backgroundColor: "#f2f2f2" }]}>
          <ActivityIndicator size = "large" color = "red" />
        </Container>
      )}
    </>
  );
};

const styles = StyleSheet.create({
  container: {
    flexWrap: "wrap",
    backgroundColor: "gainsboro",
  },
  listContainer: {
    height: height,
    flex: 1,
    flexDirection: "row",
    alignItems: "flex-start",
    flexWrap: "wrap",
    backgroundColor: "gainsboro",
  },
  center: {
    justifyContent: "center",
    alignItems: "center",
  },
});

export default ProductContainer;

Думаю жалуется на <View> for the banner of the home page <View>

Nadia Chibrikova 30.03.2021 22:43

Строка // Loading на самом деле не является комментарием, она интерпретируется как текст в JSX, и, поскольку response-native требует, чтобы весь текст был оболочкой в ​​компонентах Text, она выдает эту ошибку. Вместо этого используйте {/* Loading */} для встроенных комментариев.

azundo 30.03.2021 23:05

Нет, сэр, это действительно не помогло, я получаю ту же ошибку, я исследовал в Google, но не смог исправить свою ошибку.

Hardik poudel 31.03.2021 08:56
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
3
19
0

Другие вопросы по теме