如何从其他组件更新状态?

时间:2019-04-08 11:23:33

标签: reactjs react-native react-navigation

我正在使用react native和react导航进行路由。

如何从另一个组件/页面更新状态?

主屏幕

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();
  }

}

我的App.js以及路由和侧面菜单配置如下:

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正在执行,但不更新状态。

4 个答案:

答案 0 :(得分:2)

  

如果必须从子组件进行更新

您将必须从具有状态的组件中传递Handlers来更新值,子组件可以利用这些处理程序来更新 state < / strong>

  

如果您必须从其他位置进行更新

您将必须执行 level up 州,并遵守上述规定。

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>
  }
 }

答案 1 :(得分:0)

您可以通过使用引用来做到这一点。

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 = ()=>{
    this.homeScreen.updateState();
  }

render(){
return(
<HomeScreen ref={(ele) => this.homeScreen = ele}/>
);
}

}

答案 2 :(得分:0)

当您导航到下一个屏幕时,请以参数形式传递此功能,

&

在您的侧面菜单屏幕中,  用道具称呼它,

this.props.navigate("SideMenuScreen",{update:this.updateState});

答案 3 :(得分:0)

由于您的组件之间没有父子关系...这可以通过 Redux Action

完成
HomeScreen;

export class HomeScreen extends Component {
  constructor() {
    this.state = {
      test: ""
    };
  }

  componentWillReceiveProps(nextProps) {
    const { test: nextTest } = nextProps;
    const { test } = this.props;

    if (nextTest !== test) {
        this.setState({ test: nextTest });
    }
  }

}

const mapStateToProps = ({ yourReducerName: test }) => ({ test });
export connect(mapStateToProps)(HomeScreen);

import { HomeScreen } from "./home";
import { connect } from "tls";

class SideMenuScreen extends Component {
  updateHomeState = () => {
    const { updateHomeStateAction } = this.props;

    updateHomeStateAction({ test: 'New Value' });
  };
}

export default connect(null, { updateHomeStateAction })(SideMenuScreen);