【问题标题】:Is there any proper way to make a request when component mount or change on every component当组件在每个组件上安装或更改时,是否有任何适当的方法来发出请求
【发布时间】:2021-04-12 14:05:46
【问题描述】:

我想调用一个api请求

  • 组件挂载时
  • 在屏幕之间跳转时

这里是那个api示例代码

{
   "api_update_list": {
      "menu": "2021-04-10 04:00:24",
      "posts": "2021-04-10 04:00:34",
      "category": "2021-04-10 04:00:34",
      "products": "2021-04-10 04:00:34",
      "wishlist": "2021-04-10 04:00:34",
      "collection": "2021-04-10 04:00:34",
      "hot_items": "2021-04-10 04:00:34",
      "people": "2021-04-10 04:00:34"
   }
}

我之所以想调用那个api是因为我想检查离线数据是更新与否。我使用 react-persist 保存所有数据。假设我有 4 个组件。 (实际上,我可能有很多组件)

const ScreenA = () => {
  const dispatch = useDispatch();
  const appStatus = useSelector(state => state.app.status); //it is from redux with default value idle

    useEffect(() => {
        if ( appStatus === "idle" && isConnected ) {
            dispatch(fetchAppData()); //Data by createAsyncThunk
        }
    }, [appStatus])

    return(
        <Text>Screen A</Text>
    )
}
const ScreenB = () => {
  const dispatch = useDispatch();
  const appStatus = useSelector(state => state.app.status); //it is from redux with default value idle

    useEffect(() => {
        dispatch(statusUpdate('idle')); //I have to reset idle in every component like that to request again
    }, [appStatus])

    return(
        <Text>Screen B</Text>
    )
}
const ScreenC = () => {
  const dispatch = useDispatch();
  const appStatus = useSelector(state => state.app.status); //it is from redux with default value idle

    useEffect(() => {
        dispatch(statusUpdate('idle')); //I have to reset idle in every component like that to request again
    }, [appStatus])

    return(
        <Text>Screen C</Text>
    )
}

注意

  • 如果我将数据保存在 AsyncStorage 中,我不想再次请求数据。
  • 我会通过检查数据 api 的日期和时间来决定是否应该请求数据(api 格式示例代码在上面)。

请告诉我您遇到过这种情况。

【问题讨论】:

  • 你研究过 useFocusEffect 吗?

标签: react-native redux react-redux


【解决方案1】:

如果我理解正确,您希望在每次路线更改时都进行验证。 我的建议是使用高级监听器,这样您就不需要在每个屏幕组件上重复您的代码。

我假设您正在使用 react-navigation 库作为您的路线,在这种情况下您可以执行以下操作:

function App() {
  return (
    <NavigationContainer
      onStateChange={(state) => {
        // here you can call your validations and update your data
        // it will be called everytime the navigation state changes even on tabs switch
      }}
      initialState={initialState}
    >
      {/* ... */}
    </NavigationContainer>
  );
}

我用最常用的导航库展示了这个示例,但它们中的大多数都有等效的功能。

有关此回调的更多信息: https://reactnavigation.org/docs/navigation-container/#onstatechange

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-30
    • 2022-08-10
    • 1970-01-01
    • 2019-12-28
    • 1970-01-01
    • 2021-04-22
    • 2011-09-01
    • 2018-05-04
    相关资源
    最近更新 更多