jsky jsky - 3 months ago 26
React JSX Question

How to call componentWillUpdate() to update a child components state?

My toolbar is already rendered and i want to now call componentWillUpdate() on this toolbar when i need to update it's state?

HomeScreen

constructor(){
super();

this.state = {
pagenum: 0,
toptoolbartitle: "default",
homeviewtitle: "default",
};
}

updateHomeViewTitle(viewtitle){
console.log(viewtitle);
this.state.homeviewtitle = viewtitle;
console.log("homeviewtitle is now"+this.state.homeviewtitle);
}

render() {
return (
<View style={styles.container}>
<View style={{flex:1}}>
<TopToolbarAndroid
defaulttitle={"default"} titleupdate={this.state.homeviewtitle}/>
<RNCamera updateviewtitle={this.updateHomeViewTitle.bind(this)} />
<BottomBar />
</View>

</View>


TopToolbarAndroid

constructor(props){
super();
this.props = props;
this.state = {
pagenum: 0,
title: this.props.defaulttitle
};
}

componentWillUpdate(){
console.log("component will update?");
if (this.props.titleupdate != null)
{console.log("updating toolbar title to: "+this.props.titleupdate);
this.setState({title: this.props.titleupdate});}
}


render() {
return (
<ToolbarAndroid
title= {this.state.title}
style={styles.toolbar}
/>
);
}


Result
The componentWillUpdate is not updating the toolbars title, its not being called (re-rendered).

Answer

You need not maintain state in TopToolbarAndroid. Just do this tweak in TopToolbarAndroid to update title-

title={this.props.titleupdate ? this.props.titleupdate : this.props.defaulttitle}

Get rid of this.state too.

I'm not sure what this.props = props does in the constructor. I'd just do super(props).

Let me know, if this doesn't work. Please provide a link to runnable app as well, so that people can solve your problem effectively. Add a tag of react-native to your question to attract the right kind of people.

Host your example here - https://rnplay.org/