问题
In my React/ Redux app, I have a text input with its default value retrieved via Ajax call. User can edit the default value in the input, and then submit the updated value by clicking on a 'submit' link. I'm struggling with using either uncontrolled or controlled inputs for this.
- Using uncontrolled input with defaultValue: the component doesn't get re-rendered when the data for default value comes back from initial Ajax call (detailed in official document here). So the input field is blank all the time.
- Using controlled input with value bound to component's props: This does give the default value correctly, however since I can't change the props, the field is basically "locked". I can get around this by triggering an action to modify the global state in onChange handler and force the whole component re-rendering, but this again poses other issues. For one it seems excessive to do so in onChange, and also I don't want to commit to changing the state before user clicking the submit link.
Any suggestions what I can do here?
回答1:
As the docs say, the defaultValue
is only useful at the initial render. So if you want to use defaultValue
you have to delay the rendering of that particular component until after the data is loaded. Consider putting a loading gif (or something similar) in place of the form for the AJAX call.
I don't think the second way - using value
and updating with onChange
- is as bad as you say; it's generally how I write my forms. However, the real problem here is once again the delayed loading. By the time the initial value loads in, a user may already have filled in that input, only to see it overwritten with the received AJAX value. Not fun.
The best way in my view is simply to not use AJAX. Append your initial data to the webpage itself as a global variable. This may sound like an anti-pattern but you only ever read the global once, and it saves you cost of an AJAX request. In Redux there's a convenient way of doing this which I've documented here and here.
回答2:
Just to add to David's answer.
Sometimes it does make sense to make an AJAX call to load defaults. For ex. you could be calling some service for multi language support, creating an element in the data base with default values, etc.
I would go with the value-onChange approach and prevent the user from editing the value before it is loaded:
By disabling the input until the AJAX call returns. Just bind the disabled property to some prop that shows the default was loaded.
By not rendering the input until the AJAX call returns. When you get the default value from the server you modify the state so it triggers a re render.
来源:https://stackoverflow.com/questions/34890318/text-input-with-default-value-in-react-redux