【发布时间】:2020-07-31 20:45:12
【问题描述】:
我正在尝试应用这篇文章中给出的答案 How to parse a query string in React Router
但它不起作用。
这是我的网址:
`/api/lexemes?searchTerm=${searchTerm}&optionValue=${optionValue}`
首先,当我运行此代码时没有任何显示:
let search = window.location.search;
let params = new URLSearchParams(search);
let foo = params.get('searchTerm');
console.log(foo);
这个也没有:
let url = this.props.location.search;
let params = queryString.parse(url);
console.log(params);
当我这样做时:
console.log(this.props);
控制台显示带有搜索=“”的位置
请注意,我使用的是类组件,它只适用于功能性组件吗?如果你能告诉我如何使用类组件来做到这一点,那就太好了。
我在 App.js 中的路径现在看起来像这样:
<Switch>
<Route exact path="/" component={Main} />
...
</Switch>
我想要的是:
<Route exact path="/:search/:option" component={Main} />
这是我在 Main.js 中的 axios 调用
handleSubmit = (searchTerm, optionValue) => {
axios
.get(`/api/lexemes?searchTerm=${searchTerm}&optionValue=${optionValue}`, {
})
.then(
(res) => {
if (Array.isArray(res.data) && res.data.length === 0) {
this.setState({
noData: 1,
});
} else {
this.setState({
words: res.data,
currentScreen: "WordItem",
});
}
},
(error) => {
alert("handleSubmit error " + error);
}
);
};
【问题讨论】:
-
用
withRouterHOC 包裹你的组件。然后,您可以在 location 属性中访问查询字符串 -
我已经这样做了
标签: reactjs string parameters routes