react页面传值刷新后值消失怎么办

藏色散人
藏色散人原创
2022-12-29 11:11:591307浏览

react页面传值刷新后值消失的解决办法:1、刷新页面,查看state里面的数据是否会清空;2、通过“const name = location.query.name;const id = location.query.id;”方法在跳转链接中增加参数,即可在实现传参的同时刷新页面后数据不会丢失。

本教程操作环境:Windows10系统、react18.0.0版、Dell G3电脑。

react页面传值刷新后值消失怎么办?

解决react路由跳转传参刷新页面后参数丢失问题

import { useHistory } from 'react-router-dom';
const history = useHistory();
 
history.push({
      pathname: '/details',
      state: {
        name: name,
        id: id,
      },
});

在history中使用state确实可以传参数,在进入页面时可以正常显示,但是在刷新页面后state里面的数据会清空,页面就无法正常显示。

import { useHistory } from 'react-router-dom';
const history = useHistory();
 
history.push({
      pathname: '/details',
      query: {
        name: name,
        id: id,
      },
});

使用query是在跳转链接中增加参数,可以在实现传参的同时刷新页面后数据不会丢失,但是如果传的参数过多链接会很长。

import { useLocation } from 'react-router-dom';
const location = useLocation();
const name = location.query.name;
const id = location.query.id;
// 获取state参数的写法
const name = location.state.name;
const id = location.state.id;

这是在跳转页面获取参数的方式

(亲测有效,但是会有类型报错)

推荐学习:《react视频教程

以上就是react页面传值刷新后值消失怎么办的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。