I'd like to initiate the state value of component A based on props it received. If it didn't receive that prop, the value should be a, but if it received a certain prop, the value should be b. the state will also be used as a default value of a select of this component A, the select option will change this state, and this state value will also be passed as a prop to a child component B. May I know what would be a good solution? Should I use ComponentDidUpdate, componentWillReceiveProps to reset State, ref or any other methods? Thanks!
class ComponentA extends Component {
constructor(props) {
super(props)
this.state = {
value: "a"
}
}
componentWillReceiveProps(props) {
const someProp = props[someKey];
let someVal = someFunc(someProp);
if (someProp) {
this.setState({value:someVal})
}
}
}
...
handleChange = (val) => {
this.setState({value:val})
}
......
<select
options ={options}
value = {this.state.value}
onChange = {this.handleChange}
/>
<Input
selectVal = {this.state.value}
/>
Keep it like this , You can also use setState in condition while defining the state above
const [state, setState] = useState ('a');
if(prop.value)
setState ('a');
else
setState ('b');