react页面跳转时携带参数,返回时能展示跳转之前的数据

在React中实现页面间的参数传递和数据持久化,可以使用react-router-dom库中的useHistory和useLocation钩子。

javascript 复制代码
import React from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { Button } from 'antd';

// 页面A,跳转到页面B并传递参数
const PageA = () => {
  const history = useHistory();
  const { state } = useLocation(); // 这个state为保留操作记录的钩子 
  // 查询条件1 设置默认值state.params.paramA与getDatas()触发条件(params)一致 保证不会触发重复请求
  const [paramA, setParamA] = useState((state && state.params.paramA) || '');
  // 查询条件2 设置默认值state.params.paramA与getDatas()触发条件(params)一致 保证不会触发重复请求
  const [paramB, setParamB] = useState((state && state.params.paramB) || '');
  // 跳转到详情页时要保存的当前页的查询条件
  const [params, setParams] = useState((state && state.params) || null);

  // PageA查询数据
  useEffect(() => {
    getDatas();
  }, [params]);

  const getDatas = () => {
    getList({
      paramA,
      paramB,
    }).then(res => {
      // todo

    }).catch((err) => {
      console.log(err);
    });
  };

  const goToPageB = () => {
    history.push('/page-b', { state: { params } });
  };

  return (
    <div>
      <button onClick={goToPageB}>跳转到页面B</button>
    </div>
  );
};

// 页面B,获取参数并显示
const PageB = () => {
  const { state } = useLocation();

  return (
    <div>
      <p>传递的数据:{location.state ? location.state.params : '无数据'}</p>
      <Button type="primary" onClick={() => history.push({ pathname: '/page-a', state, })}>返回</Button>
    </div>
  );
};

export default PageA;

当从PageA跳转到PageB时,使用history.push方法并以第二个参数的形式传递了一个状态对象。在PageB中,通过useLocation钩子获取到了包含状态的location对象,并从中提取了传递的数据。从PageB返回pageA时,使用history.push方法再将pageA页面的参数返回,作为useEffect依赖项触发pageA页面的数据查询。这样,即使页面发生跳转,也能够持久化并展示出页面间传递的数据。

相关推荐
荔枝一杯酸牛奶42 分钟前
HTML 表单与表格布局实战:两个经典作业案例详解
前端·html
Charlie_lll1 小时前
学习Three.js–纹理贴图(Texture)
前端·three.js
yuguo.im1 小时前
我开源了一个 GrapesJS 插件
前端·javascript·开源·grapesjs
安且惜1 小时前
带弹窗的页面--以表格形式展示
前端·javascript·vue.js
摘星编程2 小时前
React Native鸿蒙:BiometricAuth指纹解锁实现
react native·react.js·harmonyos
摘星编程2 小时前
用React Native开发OpenHarmony应用:NFC读取标签数据
javascript·react native·react.js
GISer_Jing2 小时前
AI驱动营销:业务技术栈实战(From AIGC,待总结)
前端·人工智能·aigc·reactjs
哈哈你是真的厉害4 小时前
小白基础入门 React Native 鸿蒙跨平台开发:实现一个简单的文件路径处理工具
react native·react.js·harmonyos
GIS之路4 小时前
GDAL 实现影像裁剪
前端·python·arcgis·信息可视化
AGMTI4 小时前
webSock动态注册消息回调函数功能实现
开发语言·前端·javascript