- 该应用程序用于从API中查找有关产品的信息,可以按文章或EAN代码查找。**
用户可以在TextInput中输入商品代码或EAN或扫描条形码,并从API中获取有关产品的信息。
我遇到的问题是我无法将搜索查询从Textinput传递到上下文提供程序中的queriesString。
这是我得到的错误代码。
- 〉参考错误:找不到变量:查询字符串 *
对于我能够找到的代码应该工作,但因为它是我的第一个应用程序在React Native我最有可能错过了什么。
应用程序
App.js
import { NavigationContainer } from "@react-navigation/native";
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import HomeScreen from "./app/screens/HomeScreen";
import ScannerScreen from "./app/screens/ScannerScreen";
import { queriesContext } from "./app/global/queriesContext";
const Stack = createNativeStackNavigator();
export default function App() {
return (
<>
<queriesContext.Provider value={{ queriesString: "123456789" }}>
{console.log(queriesString + " - From App")}
<NavigationContainer>
<Stack.Navigator initialRouteName='Home' screenOptions={{ headerShown: false }}>
<Stack.Screen name='Home' component={HomeScreen} />
<Stack.Screen name='Scanner' component={ScannerScreen} />
</Stack.Navigator>
</NavigationContainer>
</queriesContext.Provider>
</>
);
}
主屏幕
HomeScreen.js
import { StyleSheet, Text, View, Image, SafeAreaView, Platform, TextInput, Button, TouchableWithoutFeedback, Keyboard } from "react-native";
import { useNavigation } from "@react-navigation/native";
import React, { useContext, useState, useEffect } from "react";
import ProductScreen from "../global/GetData";
import { queriesContext } from "../global/queriesContext";
export default function HomeScreen() {
const [queriesString, setQueriesString] = useContext(queriesContext);
const [queries, setQueries] = useState(queriesString);
const navigation = useNavigation();
const handleSearch = () => {
setQueriesString(queries);
};
ProductScreen();
//console.log(useState.q);
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<SafeAreaView style={styles.MainScreen}>
<ProductScreen />
<TextInput style={styles.TextField} editable={true} maxLength='30' numberOfLines='1' placeholder='Art no.' keyboardType='numeric' onChange={(text) => setQueries(text)} />
<Button color='red' title='Search' onPress={handleSearch} />
<View style={styles.BarcodeBox}>
<TouchableWithoutFeedback onPress={() => navigation.navigate("Scanner")}>
<Image style={styles.BarcodeImage} source={require("../assets/barcode.png")} />
</TouchableWithoutFeedback>
</View>
</SafeAreaView>
</TouchableWithoutFeedback>
);
}
const styles = StyleSheet.create({
MainScreen: {.............},
});
扫描仪屏幕
不完整,因为我无法将值从主屏幕传递到上下文。
ScannerScreen.js
import React, { Component, useState, useEffect } from "react";
import { Text, View, Alert, StyleSheet } from "react-native";
import { BarCodeScanner } from "expo-barcode-scanner";
export default function ScannerScreen() {
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
useEffect(() => {
const getBarCodeScannerPermissions = async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === "granted");
};
getBarCodeScannerPermissions();
}, []);
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
Alert.alert("Strekkode", data, [{ text: "Yes", onPress: () => setScanned(false) }, { text: "No" }]);
};
if (hasPermission === null) {
return <Text>Requesting for camera permission</Text>;
}
if (hasPermission === false) {
return <Text>No access to camera</Text>;
}
return (
<BarCodeScanner onBarCodeScanned={scanned ? undefined : handleBarCodeScanned} style={[StyleSheet.absoluteFill, styles.container]}>
<View style={styles.layerTop} />
<View style={styles.layerCenter}>
<View style={styles.layerLeft} />
<View style={styles.focused} />
<View style={styles.layerRight} />
</View>
<View style={styles.layerBottom} />
</BarCodeScanner>
);
}
const opacity = "rgba(0, 0, 0, .5)";
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: "column",
},
layerTop: {
flex: 2,
backgroundColor: opacity,
},
layerCenter: {
flex: 1,
flexDirection: "row",
},
layerLeft: {
flex: 1,
backgroundColor: opacity,
},
focused: {
flex: 10,
},
layerRight: {
flex: 1,
backgroundColor: opacity,
},
layerBottom: {
flex: 2,
backgroundColor: opacity,
},
});
获取数据
GetData.js
import { StyleSheet, Text, View, Image, SafeAreaView, Platform, TextInput, Button, TouchableWithoutFeedback, Keyboard } from "react-native";
import React, { useContext, useState, useEffect } from "react";
import { queriesContext } from "./queriesContext";
export default ProductScreen = () => {
const [queriesString] = useContext(queriesContext);
const [isLoading, setLoading] = useState(true);
const [isPromotion, setPromotion] = useState(false);
const [data, setData] = useState({
results: [BEFORE API IS CALLED NOT...],
});
console.log(queriesString + " - From GetData");
useEffect(() => {
fetch(
"SERVER.........",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"x-algolia-agent": "Algolia for JavaScript (4.13.1); Browser; JS Helper (3.10.0)",
"x-algolia-application-id": "***********",
"x-algolia-api-key": "************************",
},
body: JSON.stringify({
requests: [
{
indexName: "prod_products",
params: "query=" + queriesString,
},
],
}),
}
)
.then((respnse) => respnse.json())
.then((json) => setData(json), console.log(data))
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
//console.log(data);
//console.log(quaryString);
return (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<SafeAreaView style={styles.ProductScreen}>
<View style={styles.LogoBox}>
<Image source={require("../assets/Logo.png")} />
<Image
style={styles.ProductImage}
resizeMode='contain'
source={
isLoading
? require("../assets/fallback_266x266.png")
: {
uri: "https://................/" + data.results[0].hits[0].picture.product,
}
}
/>
</View>
<View>
<View>
<Text style={styles.Title}> {data.results[0].hits[0].name.no} </Text>
<Text style={styles.Desciption}>{data.results[0].hits[0].description.no}</Text>
<Text style={[styles.Text, styles.color]}>{data.results[0].hits[0].potentialPromotionsLabels[5110].text.no}</Text>
<Text style={styles.Text}> Price: {data.results[0].hits[0].code}</Text>
<Text style={styles.Text}> Article No: {data.results[0].hits[0].code}</Text>
<Text style={styles.Text}> EAN: {data.results[0].hits[0].ean}</Text>
</View>
</View>
</SafeAreaView>
</TouchableWithoutFeedback>
);
};
const styles = StyleSheet.create({
color: {................},
});
查询上下文
queriesContext.js
import { createContext } from "react";
export const queriesContext = createContext();
错误
ERROR ReferenceError: Can't find variable: queriesString
This error is located at:
in App (created by withDevTools(App))
in withDevTools(App)
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent)
ERROR ReferenceError: Can't find variable: queriesString
This error is located at:
in App (created by withDevTools(App))
in withDevTools(App)
in RCTView (created by View)
in View (created by AppContainer)
in RCTView (created by View)
in View (created by AppContainer)
in AppContainer
in main(RootComponent)
- 如果有人能帮忙,我将不胜感激**
1条答案
按热度按时间eivgtgni1#
我终于让它工作了。
重命名了一些东西(queriesString,setQueriesString到Quary,setQuary),只是为了更容易拼写错误。
我按照包凡晨的建议,在HomeScreen.js和GetData.js中将括号改为花括号。
在主屏幕. js中,来自
致
并在GetData.js中从
至
然后我在App.js中添加了一个组件和useState
在GetData中,我还从
这是错误的,我将其更改为正确的路径
在此之后,我仍然无法正确地更新上下文,我发现我应该在Textinput中使用onChangeText而不是onChange。
onChange导致上下文更新,但该值不是Textinput字段中的值。insted返回[object Object]。
LOG [对象对象]