简体   繁体   English

React Native Navigator,在RenderScene中调用函数时遇到麻烦

[英]React Native Navigator, trouble calling function within RenderScene

I'm using the React Native Navigator component, and I have routing set up with its renderScene method: 我正在使用React Native Navigator组件,并且已经使用其renderScene方法设置了路由:

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

Then, in my renderScene, I want to call an external method, toggleSideMenu, as shown below: 然后,在我的renderScene中,我想调用一个外部方法toggleSideMenu,如下所示:

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

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

However, toggleSideMenu is never called. 但是,从未调用toggleSideMenu。 And if I change my call from this.toggleSideMenu.bind() to this.toggleSideMenu() , I get an error stating: 如果我将呼叫从this.toggleSideMenu.bind()更改为this.toggleSideMenu.bind()this.toggleSideMenu()收到一条错误消息,指出:

Cannot update during an existing state transition (such as within render ). 在现有状态转换期间(例如在render内)无法更新。 Render methods should be a pure function of props and state. 渲染方法应该纯粹是props和state的函数。

Any ideas on how I can call an external function from within renderScene? 关于如何从renderScene调用外部函数的任何想法?

You can call a function from renderScene function without any problem. 您可以从renderScene函数调用一个函数,而不会出现任何问题。 Using this.toggleSideMenu(); 使用this.toggleSideMenu(); But what you are doing here is, you are updating the state within toggleSidemenu function. 但是您在这里所做的是,您正在更新toggleSidemenu函数中的状态。

As explained in this , 正如在解释这个

The issue is that setState will cause a re-render (potentially, depending on shouldComponentUpdate). 问题是setState会导致重新渲染(可能依赖于shouldComponentUpdate)。 If you had a setState call within the render function, it would trigger yet another render. 如果在render函数中有一个setState调用,它将触发另一个渲染。 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). 没有什么会因为某些异步操作而阻止您使用setState(事实上,这很常见)。 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). 只要它不在状态更新中运行的组件的渲染或其他生命周期方法中就可以(只要ComponentUpdate是另一个,以相同的方式导致无限循环结束),就可以了。

So if you remove setState from toggleSidemenu then function will execute without any problem. 因此,如果从toggleSidemenu中删除setState,则函数将毫无问题地执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM