How to Handle Post Request in Isomorphic React + React Router Application

前端 未结 1 1305
遇见更好的自我
遇见更好的自我 2021-01-31 05:15

I want to build Isomorphic react + react-router application and after a few days googling, now I can achieve isomorphic application that only handles G

1条回答
  •  梦谈多话
    2021-01-31 05:36

    Getting "POST" data on the client

    On the client side, you get POST data by extracting values from your form inputs in a way which corresponds to what you would have received on the server had the form been submitted normally.

    Using POST data

    So now you have your POST data, but you still have the problem that there's no way to feed the POST data into your transition hooks in React Router 0.13.x and earlier. I created a pull request for this feature which has now been closed because it was included as part of the rewrite for the upcoming v1.0 release.

    The gist of it is that locations now have a state object for squireling away any extra data you need about the current request/transition (the two are analagous) being handled:

    • On the server, you're dealing with one request at a time, so you create a static Location with data from req.body
    • On the client you pass the state object (containing extracted form data) to transitionTo().

    Now your transition hook is capable of receiving the same form data in both environments. If things go well, great! If things don't go well, you need a way to pass errors and re-render the form again. New state object to the rescue again! Use transition.redirect() and pass both input data and errors and you now have everything you need to render on both sides.

    I'm not going into more specific detail right now because v1.0 is still in beta and v0.13.x doesn't have the necessary API to do this anyway, but I have a repository which uses the pull request above to implement this workflow with 0.13.x which you could look at in the meantime:

    • isomorphic-lab - the README gives an overview of how things fit together.

    Here are some rough flow diagrams of the process, too:

    Server POST with errors and redisplay

    Server flow diagram

    Client POST with errors and redisplay

    Client flow diagram


    I've also created a few reusable modules related to this scenario:

    0 讨论(0)
提交回复
热议问题