So I update my state in a component and then pass the new props into the child but the child isn't updating correctly and the defaultValue of the input is not changing. At first I thought it might be because I am using this.props so begun using this.states and applying the new props there first but doesn't seem to be working.
Parent Component
this.state.newDetails == null ? '' :
<NewDetailsView details={this.state.newDetails} />
Child component:
import React, { Component } from 'react';
class NewDetailsView extends Component {
constructor(props) {
super(props);
this.state = {
details: (this.props.details!= null) ? this.props.details: null
}
}
componentWillReceiveProps(nextProps) {
this.setState({ details: nextProps });
this.forceUpdate();
}
render() {
return (
<div>
<input type="text" defaultValue={this.state.details.id} />
</div>
);
}
}
export default NewDetailsView ;
Solution Code:
Pending...
Issue is inside the componentWillReceiveProps
:
this.setState({ details: nextProps });
it should be :
this.setState({ details: nextProps.details });
And also remove this.forceUpdate();
, there is no need of forceUpdate
here.
Sultion to second issue change defaultValue
to just value
:
<input type="text" value={this.state.details.id} />
Here is the link to working example :
const NewDetailsView = ({details}) => (
<div>
<input type="text" value={details? details.id: null} />
</div>
);
Use getDerivedStateFromProps
instead of using deprecated componentWillReceiveProps
. An example of it can be found here
maybe as me you got into this question, In React v16.3.0 some methods became legacy (deprecated), in this example do not use this componentWillReceiveProps
, now is known as UNSAFE_componentWillReceiveProps
and can lend you through errors and bugs.
Instead look a the example below:
static getDerivedStateFromProps(nextProps, prevState) { if (nextProps.someValue !== prevState.someValue) { return { someState: nextProps.someValue, }; } else return null; } componentDidUpdate(prevProps, prevState) { if (prevProps.someValue !== this.props.someValue ) { this.setState({ someState: this.props.someValue , }); } }
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
That is the correct way of Update a component.
Ref: Replacing 'componentWillReceiveProps' with 'getDerivedStateFromProps'
defaultValue
only works for the initial load. You should controller input and use props to get value (don't need setState).
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.