详情页有个需求:设计一个 去往列表页的返回按钮
》要求 1. 如果是列表页过来的,直接返回列表页,如果原列表页带参数,也要原样返回
》要求 2. 如果是其他页面进来的,点击之后跳转到列表页
我的实现: 第一种方法:根据前一个url参数判断应该返回哪个页面
- 在其他页面跳转到详情页的时候在 history.push 里面加一个 state 参数存着、
- 在详情页面点击返回的时候先判断,是否是列表页过来的 如果是则直接返回,不是则跳转到列表页
上代码:
- 列表页的修改
history.push({
pathname: `/list/${id}/detail`,
state: { from: window.location.pathname } // 使用当前页面的 URL 作为 from 的值
});
- 详情页修改
import { useHistory } from 'react-router-dom';
const BackToList = () => {
const history = useHistory();
const backToList = () => { // 返回按钮的点击事件
const referrer = history.location.state?.from; // 拿到state的from的值
// 如果 referrer 包含 '/listname',则表示是从列表页跳转过来的,只需直接回退到上一页
if (referrer && referrer.includes('/listname')) {
history.goBack();
} else {
// 否则,去列表页
history.push({
pathname: `/listname`,
});
}
}
}
第二种方法:跳转之前把列表页的参数存进localStorage 跳转的时候直接传参跳转
- 列表页的修改
// 在跳转前保存当前页面的 URL参数 ###search
localStorage.setItem('referrerSearch', window.location.search);
// 执行跳转
history.push('`/list/${id}/detail');
2.详情页的修改
import { useHistory } from 'react-router-dom';
const BackToList = () => {
const history = useHistory();
const referrerSearch = localStorage.getItem('referrerSearch');
const backToList = () => { // 返回按钮的点击事件
history.push({
pathname: `/listname?search=${referrerSearch}`
});
} else {
// 否则,去列表页
history.push({
pathname: `/listname`,
});
}
}
}
ps:使用 localStorage 的方法适用于多种场景,尤其是在需要跨页面持久化某些数据时。不过,要注意的是 localStorage 是持久存储,如果不需要了,最好在使用后将其清除,以避免造成数据污染。