【问题标题】:In react-native, how to correctly order data-fetching and useState that depends on the data在 react-native 中,如何正确排序取决于数据的数据获取和 useState
【发布时间】:2021-09-10 05:42:11
【问题描述】:

我是 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 用于管理用户在搜索栏中键入的查询的状态。 display 和 setDisplayed 用于管理过滤项目的状态,这些项目将在搜索栏下方显示为 FlatList。

这给出了一个错误:

比上一次渲染时渲染了更多的钩子

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

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

【问题讨论】:

  • 我不明白你为什么不把状态放在返回之前?他们依赖什么?
  • @İlker [displayed, setDisplayed] 取决于数据。我想将初始状态设置为 data.alarms.items,这只有在已获取数据的情况下才有可能(在 useQuery 行中)

标签: reactjs react-native react-hooks apollo-client


【解决方案1】:
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设置。

【讨论】:

  • 感谢您的回答!我试过这个,但它给了我一个例外:未定义不是一个对象(评估'data.alarms')。当我只是在 if 语句之前移动状态管理时,我也遇到了这个错误。我认为这是因为在加载时,数据为空。有没有其他方法可以解决这个问题?再次感谢
  • 对不起,那是因为 useEffect 在它第一次渲染时起作用。我们需要进行 if 检查,我正在更新答案
  • 这就像一个魅力!谢谢伊尔克!
猜你喜欢
  • 2021-01-13
  • 2021-10-02
  • 2020-02-19
  • 2019-06-25
  • 2021-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多