You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native使用useEffect时报Expecting newline or semicolon错误如何解决

错误解决方案

语法错误原因(直接触发报错的根因)

你代码里的useEffect调用写法完全不符合JavaScript/TypeScript语法规范:

// 错误写法
useEffect(effect:()=>{
    if(originPlace && destinationPlace) {}
},deps[originPlace, destinationPlace])

effect:、deps是useEffect函数定义时的参数名和类型标注语法,只有在声明函数类型的时候才能这么写,调用函数传参时不需要写参数名,直接传对应的值即可。你写的effect:、deps[xxx]属于无效语法,JS解析器识别不了所以抛出Unexpected token错误。

修正后的useEffect写法:

useEffect(() => {
  // 两个位置都选完后执行跳转逻辑
  if(originPlace?.value && destinationPlace?.value) {
    // 此处补充你的页面跳转代码即可
  }
}, [originPlace, destinationPlace])

其他隐藏逻辑问题(修正语法后功能异常的问题)

  1. 出发地状态赋值错误:第一个GooglePlacesAutocomplete(出发地输入框)的onPress回调里,你错误调用了setDestinationPlace,导致出发地的状态永远不会更新,两个输入框都在修改目的地状态,需要改成调用setOriginPlace。
  2. 状态初始值不合理:你给useState设置的初始值是{initalState: 'null'},对象本身属于真值,originPlace && destinationPlace的判断会永远为真,页面加载就会触发跳转逻辑,建议把初始值改为null,或者判断时校验具体的属性是否存在。

完整修正后的代码

import React, {useEffect, useState} from 'react';
import {View, SafeAreaView} from 'react-native';
import {GooglePlacesAutocomplete} from 'react-native-google-places-autocomplete';

import styles from './styles';

const DestinationSearch = props => {
  // 修正初始值为null,方便后续判断
  const [originPlace, setOriginPlace] = useState(null);
  const [destinationPlace, setDestinationPlace] = useState(null);

  // 修正useEffect语法
  useEffect(() => {
    if(originPlace && destinationPlace) {
      // 在此处添加你的跳转逻辑即可,示例:
      // props.navigation.navigate('搜索结果页', {originPlace, destinationPlace})
    }
  }, [originPlace, destinationPlace])

  return (
    <SafeAreaView>
      <View style={styles.container}>
        <GooglePlacesAutocomplete
          placeholder="出发地"
          onPress={(
            data: GooglePlaceData,
            details: GooglePlaceDetail | null = null,
          ) => {
            // 修正为设置出发地状态
            setOriginPlace({data, details});
          }}
          styles={{
            textInput: styles.textInput,
          }}
          fetchDetails
          query={{
            key: 'AIzaSyB3rsn2ecpXZ8p9d8J_kLIH59rxt9KV6Rs',
            language: 'en',
          }}
        />

        <GooglePlacesAutocomplete
          placeholder="目的地"
          onPress={(
            data: GooglePlaceData,
            details: GooglePlaceDetail | null = null,
          ) => {
            setDestinationPlace({data, details});
          }}
          styles={{
            textInput: styles.textInput,
          }}
          fetchDetails
          query={{
            key: 'AIzaSyB3rsn2ecpXZ8p9d8J_kLIH59rxt9KV6Rs',
            language: 'en',
          }}
        />
      </View>
    </SafeAreaView>
  );
};

export default DestinationSearch;

内容的提问来源于stack exchange,提问作者Nitesh Raj Khanal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:18:01