React Native项目HomeScreen.js报Unexpected token语法错误求助
修复React Native食谱搜索应用的语法错误
核心错误原因
触发SyntaxError: Unexpected token, expected "}"的直接原因是JSX标签未正确闭合,导致代码语法结构混乱:
- 在
HomeScreen.js中,你创建的flex row容器<View sytle={{display: 'flex', flexDirection: 'row'}}>不仅拼错了style为sytle,还未添加闭合标签</View>,后续代码的语法逻辑因此被破坏,最终在styles定义处触发错误。
完整修复步骤
1. 闭合未完成的View标签
在<TouchableOpacity>组件之后添加</View>,闭合flex row容器:
<TouchableOpacity style={styles.button} onPress={apiCall}> <Text style={styles.buttonText}>Search</Text> </TouchableOpacity> </View> <!-- 新增:闭合flex row的View容器 --> <SafeAreaView style={{flex:1}}>
2. 修复拼写错误
- 将flex row容器的
sytle改为正确的style; - 修正API地址中的拼写错误:
searh改为search,否则API请求会返回404:
const apiUrl = `https://api.edamam.com/search?q=${searchQuery}&app_id=${apiId}&app_key=${apiKey}&from=0&to=${numberOfRecipes}&calories=591-722&health=alcohol-free`;
3. 导入缺失的组件
在HomeScreen.js顶部的导入语句中,添加未引入的核心组件:
import { Text, View, StyleSheet, TextInput, TouchableOpacity, SafeAreaView, Keyboard, // 新增:用于收起键盘 ActivityIndicator, // 新增:加载指示器 FlatList, // 新增:列表组件 Image // 新增:图片组件 } from 'react-native'
4. 修复useEffect无限循环问题
你的useEffect未设置依赖数组,会导致组件每次渲染都重复调用apiCall,添加空依赖数组让它仅在组件挂载时执行一次:
useEffect(() =>{ setLoading(true); apiCall() }, []); // 新增空数组:避免无限循环
5. 其他细节修复
- 移除
TouchableOpacity上无效的title='submit'属性(该组件不支持此属性); - 将
recipes的初始状态设为空数组,避免FlatList渲染undefined数据时报错:
const [recipes, setRecipes] = useState([]);
修复后的HomeScreen.js核心代码示例
import React, {useState,useEffect} from 'react' import { Text, View, StyleSheet, TextInput, TouchableOpacity, SafeAreaView, Keyboard, ActivityIndicator, FlatList, Image } from 'react-native' const HomeScreen = () => { const [recipes, setRecipes] = useState([]); const [searchQuery, setSearchQuery] = useState(''); const [numberOfRecipes, setNumberOfRecipes] = useState(''); const [loading, setLoading] = useState(false); const apiId = '30f0071b' const apiKey = '23e828ea96641c06655aa2f585757d1d' const apiUrl = `https://api.edamam.com/search?q=${searchQuery}&app_id=${apiId}&app_key=${apiKey}&from=0&to=${numberOfRecipes}&calories=591-722&health=alcohol-free`; async function apiCall() { setLoading(true); let resp = await fetch(apiUrl); let respJson = await resp.json(); setRecipes(respJson.hits); setLoading(false); Keyboard.dismiss(); setSearchQuery(''); } useEffect(() =>{ setLoading(true); apiCall() }, []); return ( <View style={styles.container}> <Text style={{fontSize:18, fontWeight:'bold', color:'#008080'}}> What Recipe Would You Like to Search? </Text> <View style = {{display: 'flex', flexDirection: 'row'}}> <TextInput placeholder = 'Search Recipe...' style={styles.inputField} onChangeText={ text => setSearchQuery(text)} /> <TextInput style={[styles.inputField, {width: '20%', paddingLeft:20, paddingRight:20, fontSize:18, marginLeft:10,color:'#008080', fontWeight:'bold'}]} value={numberOfRecipes} keyboardType='number-pad' onChangeText={ text => setNumberOfRecipes(text)} /> <TouchableOpacity style={styles.button} onPress={apiCall}> <Text style={styles.buttonText}>Search</Text> </TouchableOpacity> </View> <SafeAreaView style={{flex:1}}> {loading ? <ActivityIndicator size='large' color='#008080'/> : <FlatList style={styles.recipes} data={recipes} renderItem={({item}) => ( <View style={styles.recipe}> <Image style={styles.image} source={{url: `${item.recipe.image}`}} /> <View style={{padding:20,flexDirection:'row'}}> <Text style={styles.label}>{item.recipe.label}</Text> <TouchableOpacity onPress={() =>{}}> <Text style={{marginLeft:50, fontSize:20, color: '#008080'}}> Details </Text> </TouchableOpacity> </View> </View> )} keyExtractor={(item, index ) => index.toString()} /> } </SafeAreaView> </View> )} const styles = StyleSheet.create({ container: { flex:1, justifyContent:'center', alignItems:'center', padding:10, }, inputField:{ backgroundColor:'white', borderRadius:20, marginTop:10, paddingLeft:15, }, buttons:{ flexDirection:'row' }, button:{ backgroundColor:'#008080', width:'90%', alignItems: 'center', margin:15, height:45, borderRadius:15, justifyContent: 'center', marginTop:25, paddingLeft:20, paddingRight:20 }, buttonText:{ color:'white' } }) export default HomeScreen
内容的提问来源于stack exchange,提问作者user3305642
相关产品推荐
相关产品推荐

