如何使用ReactJs根据查询字符串显示数据



我有多个数据&我想按查询字符串显示数据,如何在reactJs中做到这一点?

我的代码:

const Ladies = () => {
return (
<div>
if('http://localhost:3000/ladies?service=makeup'){
<div>Makeup Content</div>
}
else('http://localhost:3000/ladies?service=hairStyling'){
<div>Hair Styling Content</div>
}      
</div>
)

}

谢谢!

我认为这是您的url

http://localhost:3000/ladies?service=makeup

在您的代码中

const params = new URLSearchParams(window.location.search)

检查它是否有查询

params.has('service')?params.get('service'):""

或记录

console.log(params.has('service')?params.get('service'):"")

返回将是makeup

我不确定,但我认为它将是字符串,所以如果你想使用它,请检查它是否等于";化妆;像这样

<div> {params.has('service')&&params.get('service')==="makeup"?"There is makeup":"There is no make up in query strings !"}</div>

更新:

你可以把它像文本一样显示div,这是jsx的一个很好的特性,这样做吧。

<div>
{params.has("service") && params.get("service") === "makeup" ? (
<div>Makeup section</div>
) : params.get("service") === "hairStyling" ? (
<div>hair styling section</div>
) : (
<div>cannot find any query strings</div>
)}
</div>

欲了解更多信息,请查看此处

最新更新