【问题标题】:Data Processing Before Rendering in React Native Functional Component在 React Native 功能组件中渲染之前的数据处理
【发布时间】:2020-11-03 03:41:57
【问题描述】:

我有一个 React Native 功能组件。

我正在使用 useEffect 从 AsycStorage 获取一些数据并将其设置为本地状态。但是,在渲染之前,我想先对这些数据进行一些处理/计算,然后才能在屏幕上渲染它。我应该在哪里做这个计算?

我的屏幕如下所示:

const BasicScreen = ({ data, getPosts }) => {

  const [myItems, setItems] = useState([]);

  const checkForItems = () => {
    var storageItems = AsyncStorage.getItem("MyItems").then((item) => {
      if (item) {
        return JSON.parse(item);
      }
    });
    setItems(storageItems);
  };

  useEffect(() => {
    async function getItems() {
      await checkForItems(); // calling function to get data from storage
    }
    getItems(); // Local Storage
    getPosts(); // Store action
  }, []);

    return (
      <View>
        <>
          <Text>{JSON.stringify(processedItemsA)}</Text>
          <Text>{JSON.stringify(processedItemsB)}</Text>
        </>
      </View>
    );
}

export default BasicScreen;

如您所见,我检查 AsyncStorage 中的项目并将该数据设置为本地状态 myItems。

我想做一些数学计算和一些条件逻辑,例如,将 myItems 的数据分成两个单独的类别,然后在屏幕上呈现。类似于processedItemsA 和processedItemsB。我应该在哪里处理数据?

processedItemsA = myItems => {
// Some logic
}

processedItemsB = myItems => {
// Some logic
}

我不确定这个逻辑应该去哪里。

请注意,这个处理是必需的,因为除了存储之外,我还从 redux 存储中获取一些数据,然后将其与这些数据一起处理。

【问题讨论】:

  • 您可以做的是创建另一个setState(),在其中从myItems 中读取数据,然后使用这些函数处理它,然后使用较新的setState() 进行设置。跨度>
  • 但是我不能在功能组件中使用setState,还是可以吗?
  • 你是在函数checkForItems()中做的。
  • useMemo 在这里是个不错的选择。它与渲染一起运行,而useEffect 在渲染之后运行。
  • 在从 AsyncStorage 而非回调中获取数据时使用 async await。 var storageItems = await AsyncStorage.getItem("MyItems");然后,您将拥有 storageItems 中的所有数据,并在同一函数中相应地对其进行处理。

标签: reactjs react-native


【解决方案1】:

这样你就可以做到这一点

const [processedItemsA, setProcessedItemsA] = useState({});
const [processedItemsB, setProcessedItemsB] = useState({});

doProcessedItemsA = myItems => {
  ...
  setProcessedItemsA({...data}); // set data after process Item A
}

doProcessedItemsB = myItems => {
  ...
  setProcessedItemsB({...data}); // set data after process Item B
}

const checkForItems = () => {
    var storageItems = AsyncStorage.getItem("MyItems").then((item) => {
      if (item) {
        const parsedItem = JSON.parse(item);
    doProcessedItemsA(parsedItem);
    doProcessedItemsB(parsedItem);
      }
    });
    // setItems(storageItems); <-- No need to set here -->
};

【讨论】:

  • 我正在以这种方式实现它。那么,函数 checkForItems 可以从 useEffect 中调用吗?
  • 是的,会从那里打来电话
  • 我可以按照上面有人的建议用 async await 重构它吗?我试过这样做,但出了点问题,数据仍未设置。
  • 是的,试试异步
猜你喜欢
  • 2020-09-13
  • 2022-01-18
  • 2020-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-06
相关资源
最近更新 更多