React native 仅在呈现组件时打开领域数据库一次(React Native)

React native 仅在呈现组件时打开领域数据库一次(React Native),react-native,react-native-android,react-hooks,realm-database,React Native,React Native Android,React Hooks,Realm Database,在为Android开发React本机应用程序时,我完全被数据库领域的问题所困扰 该应用程序允许用户通过搜索栏查询预填充的数据库。例如,键入一个名称(如“John”),然后执行对数据库的查询,返回所有名为“John”的人员 当前,在每次渲染时都会启动领域数据库,但根本不会执行: import ... const SearchBar = props => { let [inputValue, setInputValue] = useState(null); const sendIn

在为Android开发React本机应用程序时,我完全被数据库领域的问题所困扰

该应用程序允许用户通过搜索栏查询预填充的数据库。例如,键入一个名称(如“John”),然后执行对数据库的查询,返回所有名为“John”的人员

当前,在每次渲染时都会启动领域数据库,但根本不会执行:

import ...

const SearchBar = props => {
  let [inputValue, setInputValue] = useState(null);

  const sendInputValueToReduxStore = text => {
    setInputValue(text);
    props.setInputValueSearchBar(text);
  };

  const peopleSchema = {
    name: 'realm',
    properties: {
      name: 'string?',
      color: 'string?',
    },
  };

  let realm = new Realm({
    path: fs.DocumentDirectoryPath + '/default.realm',
    schema: [peopleSchema],
    readOnly: true,
  });

  const people = realm.objects('realm');
  let resultArray = [];

  const databaseRequest = () => {
    const query = inputValue;
    const result = inputValue
      ? people.filtered("name == '" + query + "'")
      : 'default';
    resultArray = Array.from(result);
    return resultArray.map(oneGuy => (
      <Text className="oneGuy" key={oneGuy.name}>
        {oneGuy.name}
      </Text>
    ));
  };

  const isText = props.text;

  return (
    <View>
      <Header searchBar rounded>
        <Item>
          <Icon name="ios-search" />
          <Input
            placeholder="Search"
            onChangeText={text => sendInputValueToReduxStore(text)}
            value={inputValue}
          />
        </Item>
      </Header>
      {isText && (
        <View>
          <Text>{props.text}</Text>
        </View>
      )}
      <View>{databaseRequest()}</View>
    </View>
  );
};   

export default SearchBar;
。。。进入一个带有空依赖项数组的
useffect()
-Hook,在第一次渲染时只创建一次领域数据库。但当我这样做时,React抱怨说“在每次渲染之后,对领域变量的赋值将丢失”

但我认为这不是什么大问题,因为我只想打开并查询数据库


我读过关于使用
useRef()
-Hook解决上述问题的文章,但我想知道我的整个方法是否有意义(只打开一次数据库)。让上面的组件保持原样,而不考虑其生命周期阶段是否更好

好的,您可以传递一个空数组作为第二个参数,告诉React您的效果不依赖于来自props或state的任何值,因此它永远不需要重新运行

useEffect(() => {

    /* your code */

}, []); // run an effect and clean it up only once (on mount and unmount)

这也是我的想法,就像我在帖子中指出的那样。但不幸的是,它给出了一个错误:“…但是当我这样做时,React抱怨说”在每次渲染之后,对领域变量的赋值将丢失“…”
useEffect(() => {

    /* your code */

}, []); // run an effect and clean it up only once (on mount and unmount)