【问题标题】:React Native Expo - Setting an Initial Value Before Variable AssignmentReact Native Expo - 在变量赋值之前设置初始值
【发布时间】:2021-10-14 02:37:24
【问题描述】:

使用 React Native Expo,我有一个 MapView 屏幕,它在底部屏幕上显示标记(标题、描述、图像等)的信息。目前我有一个功能,当按下标记时,标记信息将传递给名为 MarkerInfo 的变量并显示在底部屏幕上。但是,当组件初始化时,底页中不会显示任何信息。

我想显示一条提示用户选择标记的消息。

这是包含 pressMarker 函数的当前代码块:

// ## Attempting to set intial values prompting users to select a marker for more info
const state = {
   MarkerInfo: {
      PreviewTitle: "Select A Marker.",
      Description: "Press on a marker to get location information"
   }
};

// ## Without the code above this all works fine:

// ## Setting the currently selected marker as variable (in an array) "MarkerInfo".
const [MarkerInfo, setMarkerInfo] = useState([]);

const pressMarker = (i) => {
   setMarkerInfo(i);
   console.log(i)
   return(MarkerInfo)
 };

下面是标记信息数组的示例,当标记被按下时。

Object {
  "Description": "Former historic palace housing huge art collection, from Roman 
   sculptures to da Vinci's 'Mona Lisa.",
  "ImageUrl": "*** My firebase storage URL",
  "Latitude": 48.86074344,
  "Location": "Paris",
  "Longitude": 2.337659481,
  "PreviewTitle": "Louvre",
  "Title": "Louvre Museum",
  "id": 64,
  "key": "63",
}

但是,在我击中标记之前,底部的工作表没有显示任何内容。所以看起来我对标记信息的初始变量定义没有像我希望的那样执行。

我需要对初始声明进行哪些更改?我也尝试过使用组件确实安装并返回初始标记信息的功能,但没有运气。

【问题讨论】:

    标签: javascript react-native expo state use-state


    【解决方案1】:

    如果您使用钩子,则不需要使用像 componentDidMount 这样的生命周期方法。当您按照 React 的建议使用钩子和功能组件时,您尝试初始化状态的方式似乎是错误的。

    当您从数组中选择一个项目时,您必须传递与状态对象相同的对象,作为useState 声明中的初始值。

    所以你的代码应该是

    const initialState = {
      "Description": "Press on a marker to get location information",
      "ImageUrl": "",
      "Latitude": 0,
      "Location": "",
      "Longitude": 0,
      "PreviewTitle": "Select A Marker.",
      "Title": "Select A Marker.",
      "id": 0,
      "key": "",
    }
    
    const [MarkerInfo, setMarkerInfo] = useState(initialState);
    

    ps 我假设您的 PreviewTitle 和 Description 是您在屏幕上显示的内容

    【讨论】:

      【解决方案2】:

      尝试使用

      setMarkerInfo([...i]);

      改为使用

      setMarkerInfo(i);

      【讨论】:

      • 当按下标记时,不幸的是这给了我错误 TypeError: Invalid attempt to spread non-iterable instance。为了可迭代,非数组对象必须有一个 [Symbol.iterator]() 方法。而且似乎没有设置初始值。
      猜你喜欢
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-30
      • 2011-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多