【发布时间】:2020-01-15 08:05:18
【问题描述】:
编辑:发布了我如何解决这个问题的答案,而不是使用 react-router 可选参数。
由于某种原因,当我使用附加到 URL 的可选参数转到可选的 react-router 路由/url 时,我遇到了 GET 错误。我试图通过在 URL 中包含可选参数 SRC 来跟踪用户的来源。我已经尝试了 /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
})
);
}
这是我运行 axios GET 请求的 componentDidMount() 内部的内容,然后还检查可选参数并将其存储在 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,为什么会出现?
感谢任何帮助,谢谢!
【问题讨论】:
标签: javascript reactjs react-router