ReactJS with React Router - strange routing behaviour on Chrome

前端 未结 1 489
萌比男神i
萌比男神i 2020-12-11 09:43

This is a bit weird and I would like to get to the bottom of it.

I have a page where users type in their email address and click a button and then I show \"you\'re

相关标签:
1条回答
  • 2020-12-11 10:14

    Just faced this problem a few hours ago.

    So you have something like that in your component (es6 syntax):

    render() {
        return (
            <form onSubmit={ this.submit.bind(this) }>
                { /* inputs stuff here */ }
            </form>
        );
    }
    
    submit() {
        // Ajax request here
    }
    

    The problem is that Chrome try to send a get request, and appends a ? to your current URL, because you don't have any action="/formsubmit" in your form tag and it thinks it is a method="get", by default. So Chrome take the current URL (for example myapp.com/#/) and tries to send form at myapp.com/?#/, which is a new URL.

    To prevent that, simply add a preventDefault when you submit your form

    submit(e) {
        e.preventDefault()
        // Ajax request here
    }
    
    0 讨论(0)
提交回复
热议问题