gpt4 book ai didi

javascript - 可选的 react 路由器参数标记 GET 请求错误?

转载 作者:行者123 更新时间:2023-11-30 06:12:46 26 4
gpt4 key购买 nike

编辑:发布了我如何解决这个问题而不是使用 react-router 可选参数的答案。

出于某种原因,当我使用附加到 URL 的可选参数转到可选的 react-router 路由/url 时,我遇到了 GET 错误。我试图通过将可选参数 SRC 包含到 url 来跟踪用户的来源。我已经尝试了从/ref=testing、/src=testing、/testing 到 :referrer?他们可能会保存在 localStorage 中,但仍会引发控制台 GET 请求。

这是我的 App.js 的样子:

<Route exact path="/profile/user/:user/:referrer?" component={ ProfileById } />

:user是mongoose结构体中的用户ID。 :推荐人?是 src=(不管它是什么)

这是我对路线的 axios 请求:

export const getProfileByUserId = (user) => dispatch => {
dispatch(setProfileLoading());
axios.get(`/profile/user/${user}`)
.then(res =>
dispatch({
type: GET_PROFILE,
payload: res.data
})
)
.catch(err =>
dispatch({
type: GET_PROFILE,
payload: null
})
);
}

这是我的 componentDidMount() 中的内容,我在其中运行 axios GET 请求,然后还检查可选参数并将其存储在 localStorage 中。

componentDidMount() {
if (this.props.match.params.user) {
this.props.getProfileByUserId(this.props.match.params.user);
}

if (this.props.match.params.referrer) {
let referrerString = this.props.match.params.referrer.split('=');
localStorage.setItem('referrer', referrerString[1])
}
}

当我加载路由时,假设它是:/profile/user/20385h1058h385/ref=testing GET 错误出现为:404 Not found,然后说错误是/ref=testing 如果它是一个可选参数而且我实际上并没有在这个可选参数上请求 GET,为什么它会出现?

感谢任何帮助,谢谢!

最佳答案

请仅在 URL 中附加 testing 而不是 ref=testing。在这种情况下,您的网址将为 /profile/user/20385h1058h385/testing

我们将 : 用于必需参数,将 :parameter_name? 用于可选参数。

例如:

<Route path="/login/:p1/:p2?" component={Login} />

这里p1是必填参数,p2是可选参数。

我们像您一样在 componentDidMount 方法中获取它们。

this.props.match.params.p1

关于javascript - 可选的 react 路由器参数标记 GET 请求错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57923747/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com