react-native 函数式组件中哪里实现初始化代码

Where to implement initialization code in react-native functional component

我正在遵循 expo 项目创建向导给出的功能模式,并且我有一个这样的组件:

Search.js

export default function Search() {
   const [searchResults, setSearchResults] = React.useState(buildContentViews(contents));

   return (
      <View style={styles.container}>
         <ScrollView contentContainerStyle={styles.contentContainer}>
            <View style={styles.statusLine}>
               <Text style={styles.statusLineText}>{(pageInfo.numResults || 0) + ' Treffer'}</Text>
            </View>
            {searchResults}
         </ScrollView>
      </View>
   );
}

现在我有一些后端 REST 服务的非反应本机实现,它将定期更新搜索结果。因此我需要做类似的事情:

export default function Search() {
   const [searchResults, setSearchResults] = React.useState(buildContentViews(contents));

   client.events.on('searchResults', (results) => setSearchResults(results));

   return (
      <View style={styles.container}>
         <ScrollView contentContainerStyle={styles.contentContainer}>
            <View style={styles.statusLine}>
               <Text style={styles.statusLineText}>{(pageInfo.numResults || 0) + ' Treffer'}</Text>
            </View>
            {searchResults}
         </ScrollView>
      </View>
   );
}

但是我很快就得到了建立太多事件监听器的错误,这可能是因为上面的代码在每次(重新)渲染组件时都会得到 运行,或者换句话说,每当组件已更新。

那么在这种情况下如何正确注册事件监听器and/or注销事件监听器?

useEffect hook 是你的朋友!

这就是我处理 registering/deregistering 到 react-navigation 事件在屏幕之间移动的方式(我不知道你的 client 代码是如何工作的,这个只是一个例子)

  useEffect(() => {
    const onFocus = () => {
      // here I do something when the screen gets focused
    }
    // this is how you handle the registration to the event
    const focusListener = navigation.addListener('didFocus', onFocus)

    // and this is how to handle deregistration!
    return () => focusListener.remove()

  }, []) // empty array of dependencies
  1. useEffect 钩子的主体中,您定义您的操作;
  2. return函数用于清理效果,是移除事件监听器的完美地方;
  3. 依赖项的空数组 向您保证这段代码只会执行一次(在第一次渲染之后),不会再执行了!不再重新分配!定义事件侦听器的完美方式!