How to handle early input to isomorphically rendered forms

大城市里の小女人 提交于 2019-12-05 03:35:06

I suppose I could put refs on every input and copy their values into the application state on componentDidMount, but there has got to be a better way. Has anyone else solved this problem?

Browsers autofilling fields or remembering previous values across refreshes can also cause what is effectively the same issue - your app's view of the data being different from the user's.

My brute-force solution in the past has been to extract the complete form state from its inputs onSubmit and re-run validaton before allowing submission to proceed.

Using componentDidMount as you suggest sounds like a more elegant solution as it avoids the user entering invalid data and being allowed to try to submit it before they get any warnings. You don't need to add a ref to every input, though; just add one to the <form> and use its .elements collection to pull all the data.

Suggested solution:

  1. In componentDidMount(), pull the form's data from its .elements (I extracted get-form-data from my form library for this purpose)
  2. Check each field's current value against what's in your app's state.
  3. If a field's current value is different, treat it just as you would new user input arriving via an event - update it in state and re-run any associated validation routines.

Then from componentDidMount() onwards, your app and the user will always be on the same page (literally).

Matthew King

If I understand you correctly, this is what is happening: https://jsfiddle.net/9bnpL8db/1/

var Form = React.createClass({
    render: function () {
        return <div>
            <input type="text" defaultValue={this.props.defaultValue}/>
        </div>;
    }
});

// Initial form render without server-side data
React.render(<Form/>, $('#container')[0]);

setTimeout(function () {
    // Simulate server-side render
    $('#container').html(
        // overwrites input
        React.renderToString(<Form defaultValue="server1"/>)
    );
}, 5000);

Server-side rendering should not be used to make updates. Rather, server-side rendering should be used to create the initial page, populating the inputs before the user ever has a chance to make changes. To solve your problem, I think you have a couple of options:

  1. Use server-side rendering to render the initial page, prepopulating the input with saved data. With this option, the user does not ever see the page without the saved data. This removes the issue where the user starts entering input and then has that input overwritten by the server.
  2. Use client-side rendering to render the page and use a GET request to get the prepopulated data, updating the input if the user hasn't already entered some input.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!