Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update state from other component?

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.

like image 658
Khurshid Ansari Avatar asked Apr 08 '19 11:04

Khurshid Ansari


1 Answers

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>
  }
 }
like image 101
Praveen Rao Chavan.G Avatar answered Sep 23 '22 06:09

Praveen Rao Chavan.G