Reactjs 希望将用户发送到另一个页面,且该页面处于react中的特定状态
我的主页上有一个按钮,效果很好:Reactjs 希望将用户发送到另一个页面,且该页面处于react中的特定状态,reactjs,button,state,react-router-dom,Reactjs,Button,State,React Router Dom,我的主页上有一个按钮,效果很好: <Link to="/pageItShouldRedirectTo"> <button class="buttonStyling"> Click to read article 3 </button> </Link> 点击阅读第3条 它将用户发送到pageItShouldRedirectTo。在pageItShouldRedi
<Link to="/pageItShouldRedirectTo">
<button class="buttonStyling">
Click to read article 3
</button>
</Link>
点击阅读第3条
它将用户发送到pageItShouldRedirectTo。在pageItShouldRedirectTo上,我有一个按钮列表,可以在下面的空白处呈现不同的组件:
function ArticleSelection() {
const [displayComponent, setDisplayComponent] = useState(null);
return (
<Button onClick={() => setDisplayComponent(<Article1/>)}>Click to see Article 1</Button>
<Button onClick={() => setDisplayComponent(<Article2/>)}>Click to see Article 2</Button>
<Button onClick={() => setDisplayComponent(<Article3/>)}>Click to see Article 3</Button>
{displayComponent}
)}
export default ArticleSelection
函数ArticleSelection(){
const[displayComponent,setDisplayComponent]=useState(null);
返回(
setDisplayComponent()}>单击以查看文章1
setDisplayComponent()}>单击以查看第2条
setDisplayComponent()}>单击以查看第3条
{displayComponent}
)}
导出默认项目选择
这个部分本身也很好用。我单击一个按钮,它在{displayComponent}中呈现组件。但当我使用主页上的按钮时,我希望它将其与已呈现的第3条一起发送
我已经尝试了几种方法,但都没有成功。有三种方法可以解决这个问题:
链接
重定向,在这种情况下更方便
import url from 'url'
const whereToRedirect = url.format({
pathname: `/pageItShouldRedirectTo`,
query: {
article: "third",
},
})
// whereToRedirect should look something like this: /pageItShouldRedirectTo?article=third
...
<Link to={whereToRedirect }>
<button class="buttonStyling">
Click to read article 3
</button>
</Link>
const search = new URLSearchParams(props.location.search)
const article = search.get("article")