gpt4 book ai didi

javascript - React Native Navigator,在 RenderScene 中调用函数时遇到问题

转载 作者:行者123 更新时间:2023-11-29 00:57:48 26 4
gpt4 key购买 nike

我正在使用 React Native Navigator 组件,并且我使用它的 renderScene 方法设置了路由:

<Navigator
ref="navigator"
initialRoute={{name:'Main'}}
renderScene={(route,navigator)=>this.renderScene(route,navigator)} />

然后,在我的 renderScene 中,我想调用一个外部方法 toggleSideMenu,如下所示:

toggleSideMenu() {
this.setState({
menuDisableGestures: false
});
}

renderScene(route, navigator) {
switch (route.name) {
case "SecondView":
this.toggleSideMenu.bind()
return <SecondView navigator={navigator} />
....

但是,从未调用 toggleSideMenu。如果我将调用从 this.toggleSideMenu.bind() 更改为 this.toggleSideMenu(),我会收到一条错误消息:

无法在现有状态转换期间更新(例如在 render 内)。渲染方法应该是 Prop 和状态的纯函数。

关于如何从 renderScene 中调用外部函数有什么想法吗?

最佳答案

您可以毫无问题地从 renderScene 函数调用函数。使用 this.toggleSideMenu();但是您在这里所做的是,您正在更新 toggleSidemenu 函数中的状态。

this 中所述,

The issue is that setState will cause a re-render (potentially, depending on shouldComponentUpdate). If you had a setState call within the render function, it would trigger yet another render. You'd likely end up in an infinite loop of re-renderings. There's nothing that stops you from using setState as a result of some asynchronous operation (in fact it's very common). It's fine just as long as it's not in the render or some other lifecycle method of a component that is run on a state update (shouldComponentUpdate being another as you'd end up with an infinite loop in the same way).

因此,如果您从 toggleSidemenu 中删除 setState,则函数将毫无问题地执行。

关于javascript - React Native Navigator,在 RenderScene 中调用函数时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37450496/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com