我正在使用 native react 和 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以及路由和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正在执行,但不更新状态。
最佳答案
由于您的组件之间没有父子关系,因此可以通过 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);
关于reactjs - 如何从其他组件更新状态?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55572323/