0

在为 Android 开发一个 React Native 应用程序时,我完全被一个关于数据库领域的问题所困扰。

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

目前,Realm 数据库在每次渲染时都会启动,这根本不是高性能的:

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;

所以,我想把这些部分:

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

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

...进入一个useEffect()带有空依赖数组的 -Hook 以在第一次渲染时只创建一次 Realm 数据库。但是当我这样做时,React 抱怨“每次渲染后对领域变量的赋值都会丢失”。

在此处输入图像描述

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

我阅读了有关使用useRef()-Hook 解决上述问题的信息,但我想知道我的整个方法是否有意义(只打开一次数据库)。将上面的组件保持原样而不关心它的生命周期阶段会更好吗?

4

1 回答 1

0

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

useEffect(() => {

    /* your code */

}, []); // run an effect and clean it up only once (on mount and unmount)
于 2020-02-06T22:16:09.817 回答