最佳的方式在React中从一个页面传递props到另一个页面是什么?

huangapple go评论75阅读模式
英文:

What's the best way to pass props from one page to another in react?

问题

Sure, here's the translated content:

我正在编写一些基于React的代码,这是我的要求:

我想要提交一个表单并将表单传递给API,
当我成功提交时,
我想要被重定向到另一个页面,并显示一个消息,告诉我表单已成功提交,但在这条消息中,我想要显示表单标题(我之前输入的)。

所以我的问题是:在React中传递字段到新页面的最佳方法或更好的方法是什么?
我知道一些方法,比如:

  1. 通过路由状态传递
  2. 使用上下文

还有其他的方法吗?在React中推荐使用哪一种?
谢谢!

希望我能从ReactJs团队得到更多建议,谢谢!

英文:

I'm writing some code based on react, here is my requirement:

I wanna submit a form and pass the form to api,
when I summit successfully,
I want to be redirected to another page, and show a message that tells me the form is submit successfully, but in this message, I wanna show the form title (I entered before).

So my question is: what's the best way or better way to pass the field to the new page in React?
I know some ways, like:

  1. pass it through route state
  2. use context

Is there any other way to do this? And which is recommended in React?
Thanks!

Hope I can get some more suggestions from ReactJs Team, thanks!

答案1

得分: 1

你可以使用Redux来存储formTitleState,初始值为空字符串。这个状态将在你的应用程序中随处可访问。你可以使用onchange事件监听器来监听输入标题的输入字段,以将表单标题状态更改为你在输入中输入的内容。在向API发送成功的POST请求之后,可以使用类似于<Navigate to="/success" />的方式来使用react-router-dom将用户推向其他页面。由于formTitleState在全局范围内可访问,你可以在成功页面中使用它并在UI中显示它。

希望这有所帮助。

英文:

You can use Redux to store the formTitleState

which initially will be an empty string. The state will be accessible everywhere in your app. You can use the onchange event listener to the input field where you are entering the title to change the form title state to whatever you enter in the input. After the post request to the API is successful, use something like

<Navigate to="/success" />

from react-router-dom to push the user to the other page. Since the formTitleState is accessible globally, you can use it in the success page or and show it in the UI.

I hope this helps.

huangapple
  • 本文由 发表于 2023年1月6日 13:53:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75027416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定