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

问题描述 投票:4回答:4

我正在使用react native并对路由进行反应。

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

主屏幕

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和路由和sidemenu配置如下:

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

reactjs react-native react-navigation
4个回答
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);

2
投票

如果必须从子组件更新

你必须从保存状态的组件传递Handlers来更新值,子组件可以利用这些处理程序来更新状态

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

你将不得不做一个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>
  }
 }

0
投票

你可以使用ref来做到这一点。

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

}

0
投票

导航到下一个屏幕时,在params中传递此功能,

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

在侧边菜单屏幕中,使用道具调用它,

this.props.navigation.state.params.update();//you can pass params also if needed
© www.soinside.com 2019 - 2024. All rights reserved.