#node.js #reactjs #react-native #api #node-modules
Вопрос:
Это приложение react-native, работает без ошибок, когда API не вызывается, ошибки возникают только при запуске API, созданного с помощью NodeJS. Я получаю ошибку, так как текстовые строки с ошибкой вызова API должны отображаться в компоненте.
Ниже приведена ошибка, отображаемая в консоли, где я запускаю приложение react-native
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_modulesreact-nativeLibrariesLogBoxLogBox.js:148:8 in registerError
at node_modulesreact-nativeLibrariesLogBoxLogBox.js:59:8 in errorImpl
at node_modulesreact-nativeLibrariesLogBoxLogBox.js:33:4 in console.error
at node_modulesexpobuildenvironmentreact-native-logs.fx.js:27:4 in error
at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:104:6 in reportException
at node_modulesreact-nativeLibrariesCoreExceptionsManager.js:171:19 in handleException
at node_modulesreact-nativeLibrariesCoreReactFiberErrorDialog.js:43:2 in showErrorDialog
at node_modulesreact-nativeLibrariesRendererimplementationsReactNativeRenderer-dev.js:15258:32 in logCapturedError
at [native code]:null in dispatchAction
at ScreensProductsProductContainer.js:44:10 in axios.get.then$argument_0
at node_modulesreact-nativenode_modulespromisesetimmediatecore.js:37:13 in tryCallOne
at node_modulesreact-nativenode_modulespromisesetimmediatecore.js:123:24 in setImmediate$argument_0at node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:130:14 in _callTimer
at node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:181:14 in _callImmediatesPass
at node_modulesreact-nativeLibrariesCoreTimersJSTimers.js:441:30 in callImmediates
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:387:6 in __callImmediates
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:135:6 in __guard$argument_0
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:364:10 in __guard
at node_modulesreact-nativeLibrariesBatchedBridgeMessageQueue.js:134:4 in flushedQueue
at [native code]:null in flushedQueue
at [native code]:null in callFunctionReturnFlushedQueue
Вот скриншот ошибки, показанной в мобильном приложении
И код, указанный в ошибке, является
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.log("Api call error");
});
// Categories
axios
.get(`${baseURL}categories`)
.then((res) => {
setCategories(res.data);
})
.catch((error) => {
console.log("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;
Комментарии:
1. Я думаю, что он жалуется на
<View> for the banner of the home page <View>
2.
// Loading
Строка на самом деле не является комментарием, она интерпретируется как текст в JSX, и поскольку react-native требует, чтобы весь текст был оберткой вText
компонентах, она выдает эту ошибку. Вместо этого используйте{/* Loading */}
для встроенных комментариев.3. Нет, сэр, это действительно не помогло, я получаю ту же ошибку, я исследовал Google, но не смог устранить свою ошибку.
Ответ №1:
Я решаю эту ошибку, изменив свою среду разработки. Когда я перехожу с VS-кода на sublime text или notepad или android studio, эта ошибка устраняется.