要实现这个功能,你可以按照以下步骤进行操作:

  1. 首先,创建一个 React 类组件,并在其中创建一个状态变量(store)来存储请求的结果。例如:
import React, { useEffect, useState } from 'react';

const MyComponent = () => {
  const [store, setStore] = useState(null);

  useEffect(() => {
    // 在组件加载时请求接口并更新 store
    fetchData();
  }, []);

  const fetchData = () => {
    // 发送请求获取数据,并更新 store
    // 例如使用 fetch 或 Axios 进行请求
    fetch('your-api-url')
      .then(response => response.json())
      .then(data => setStore(data))
      .catch(error => console.log(error));
  };

  useEffect(() => {
    if (store) {
      // 根据 store 的值进行页面跳转
      // 例如使用 React Router 进行页面跳转
      if (store === 'page1') {
        // 页面跳转到 page1
        // 例如使用 useHistory Hook
        history.push('/page1');
      } else if (store === 'page2') {
        // 页面跳转到 page2
        history.push('/page2');
      }
    }
  }, [store]);

  return (
    <div>
      {/* 渲染页面内容 */}
    </div>
  );
};

export default MyComponent;
  1. 在组件加载时使用 useEffect 钩子函数来发送请求并更新 store 的值。在 useEffect 中使用空的依赖数组 [] 来确保请求仅在组件加载时发送一次。

  2. 在 fetchData 函数中发送请求,并在请求成功后使用 setStore 函数来更新 store 的值。

  3. 创建第二个 useEffect 钩子函数,监听 store 的变化。当 store 的值发生变化时,根据 store 的值进行页面跳转。你可以根据 store 的值使用 React Router 或其他方式进行页面跳转。

  4. 最后,在组件的返回值中渲染页面内容。

注意:在上述代码中,我使用了一些示例代码来演示如何进行页面跳转。具体的实现方式可能因你所使用的路由库和项目结构而有所不同。请根据你的实际情况进行相应的修改。

React 类组件:使用 store 存储数据并根据接口结果跳转页面

原文地址: https://www.cveoy.top/t/topic/pdxa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录