简体   繁体   中英

React input defaultValue doesn't update with props changes

I have created an app using React, Redux & React Router. When the URL changes, the value of the query parameter personId should be used to get the correct person object from an array:

mapStateToProps = (state, router) => ({
    onePerson: state.persons.filter((person, i) => person.id === router.params.personId)[0]
})

I also have an input element that depends on that person's name:

<input type="text" defaultValue={this.props.onePerson.name} />

As the URL changes, and the props updates accordingly, the input element's defaultValue doesn't change. How can I overcome this issue? Note that I don't want to use "controlled input".

That's because the defaultValue is only used the first time the component gets rendered. If you need to update the value later, you have to use a controlled input.

Update:

From the React Docs :

The defaultValue and defaultChecked props are only used during initial render. If you need to update the value in a subsequent render, you will need to use a controlled component.

I guess you could remove and re-add the component to give it a new defaultValue , but you really shouldn't .

I find easy to destroy an element, clean all data and replace it with the new one with :

ReactDOM.unmountComponentAtNode(document.querySelector("#myParentElement"));

        if(document.querySelector("#myParentElement")){
            ReactDOM.render(
                <MyComponent name={name}  />,
                document.querySelector("#myParentElement")
            );
        };

You can use also this version of unmount method:

ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM