在 react-native 中,如何正确排序数据获取和依赖于数据的 useState

In react-native, how to correctly order data-fetching and useState that depends on the data

我是 react-native 的新手,如果这是一个愚蠢的问题,我深表歉意。

我有以下代码(只显示相关部分):

const Alarms = () => {

  var { loading, error, data } = useQuery(ALARMS_QUERY) // this line fetches data with Apollo Client
  if (loading) return <Text>Loading...</Text>;
  if (error) return <Text>Error :(</Text>;

  const [query, setQuery] = React.useState("");
  const [displayed, setDisplayed] = React.useState(data.alarms.items)

  ...
}

query 和 setQuery 用于管理用户在搜索栏中键入的查询的状态。 displayed 和 setDisplayed 用于管理将在搜索栏下方显示为 FlatList 的筛选项的状态。

这给出了一个错误:

Rendered more hooks than during the previous render

而且我理解这是因为我将状态管理放在两个 if 语句之后。但是,如何解决这个问题?我不能将状态管理放在 if 语句之前,因为它取决于数据的存在。

有人可以帮助我吗?谢谢!

const Alarms = () => {

  var { loading, error, data } = useQuery(ALARMS_QUERY) // this line fetches data with Apollo Client
 const [query, setQuery] = React.useState("");
 const [displayed, setDisplayed] = React.useState("")

  useEffect(()=> {
if(data){
  setDisplayed(data.alarms.items)
}

                 }, [data])


  if (loading) return <Text>Loading...</Text>;
  if (error) return <Text>Error :(</Text>;

 

  ...
}

可以先设置显示状态为空字符串,如果数据是异步过来的,可以稍后用useEffect设置。