I am using react native and react navigation for routing.
How to update state from another component/page?
HomeScreen
export class HomeScreen extends Component {
constructor(){
this.state = {
test: ''
}
}
updateState = ()=>{
this.setState({test:'new value'});
}
}
SideMenuScreen
import { HomeScreen } from "./home";
export class SideMenuScreen extends Component {
updateHomeState = ()=>{
let oHome = new HomeScreen();
oHome.updateState();
}
}
My App.js and routing and sidemenu config as below :
import { createAppContainer, createDrawerNavigator } from "react-navigation";
import { SideMenuScreen } from "./screens/Sidemenu";
import { HomeScreen } from "./screens/Home";
export default class App extends Component {
render() {
return(
<AppContainer></AppContainer>
);
}
}
const AppNavigator = createDrawerNavigator(
{Home: HomeScreen,
other: otherpage},
{
contentComponent: SideMenuScreen
}
);
const AppContainer = createAppContainer(AppNavigator);
updateState executing but not updating state.
If you have to update from the child component
You will have to pass down the Handlers
from the component which holds the state to update the values, child component can make use of these handlers to update the state
If you have to update from some other location
You will have to do a level up the State and follow the same has above.
LevelUpComponent
export class App extends Component {
constructor(){
this.state = {
test: ''
}
}
updateState = (values)=>{
this.setState(values);
}
render(){
return <div>
<HomeScreen></HomeScreen>
<SideMenuScreen updateState={this.updateState}></SideMenuScreen>
</div>
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With