如何解决希望将用户发送到具有特定状态的另一个页面以做出反应
所以我在主页上有这个按钮,效果很好:
<Link to="/pageItShouldRedirectTo">
<button class="buttonStyling">
Click to read article 3
</button>
</Link>
它将用户完美地发送到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
本节也很有效。我单击一个按钮,它将在{displayComponent}中呈现该组件。但是,当我使用主页上的按钮时,我希望它与已渲染的第3条一起发送。
我已经尝试了几种方法,但无法使其正常工作。
解决方法
有3个解决方法:
-
最简单,用途最少的是“提升状态”,如here in the react docs所述。将包含有关所显示文章的信息的状态上移到公共父级。
-
使用react上下文(或任何用于共享状态存储的库,例如react-redux)。 Here is react context documentation。您可以设置在此类共享状态存储中显示的文章。
-
在网址中传递数据:
在源组件中:
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")
不要忘记用withRouter进行换行以确保props.location存在或使用useLocation钩子。
另外,您可以使用useHistory而不是Link
进行重定向,在这种情况下更方便。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。