【问题标题】:react-native-router-flux throws Actions.callback is not definedreact-native-router-flux 抛出 Actions.callback 未定义
【发布时间】:2016-09-01 22:42:10
【问题描述】:

运行以下 sn -p 导致路由器抛出

import React from 'react';
import {Scene, Router} from 'react-native-router-flux';

export default App extends React.Component {
  componentDidMount() {
      // This fails
      Actions.login();
  }

  render() {
    return (
      <Router>
        <Scene key="root" hideNavBar>
          <Scene key="login" component={Login} />
          <Scene key="main" component={Main} initial />
        </Scene>
      </Router>
    );
  }
}

路由器应该已经被 App.componentDidMount 挂载了,所以所有的动作都应该可以正常工作。
如果我将超时设置为 2 秒,那么它确实有效。 有人遇到过吗?我在这里做错了吗?

【问题讨论】:

    标签: react-native react-native-router-flux


    【解决方案1】:

    所以我终于明白了问题所在。
    问题不在于场景需要时间来初始化。
    Action.login 需要在根 componentDidMount 之后的第一次实际渲染之后路由器注入的 Actions.callback。

    会发生以下情况:
    调用根渲染函数
    在没有 state.reducer 的情况下调用路由器渲染函数,所以什么都不做。
    路由器 componentDidMount 被调用 - 这里 Actions 被初始化并且 reducer 被保存到状态(setState 是异步的)。
    根组件DidMount - 这里的回调仍未初始化。
    调用路由器渲染 - 此调用由之前的 setState 触发。现在 Actions.callback 被注入。

    所以在第二次渲染之后,路由器就被初始化了。

    我设法找到了比任意 setTimeout 更好的解决方案。
    你重写 Router 的 render 方法,并在它用数据渲染后,通知父级:

    class OverrideRouter extends Router {
        constructor(props) {
            super(props);
            this.render = this.overrideRender;
        }
        overrideRender() {
            const result = super.render();
            if (!result) {
                return result;
            }
            // after first initialization use the regular render.
            this.render = super.render;
            if (this.props.onRouterInitialize) {
                // need this setTimeout to allow this method to complete so that the Actions.callback is populated
                setTimeout(this.props.onRouterInitialize, 10);
            }
            return result;
        }
    }
    

    编辑
    我设法完全解决了这个问题并发送了一个拉取请求来解决它。 https://github.com/aksonov/react-native-router-flux/pull/1137

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2020-12-20
      • 1970-01-01
      相关资源
      最近更新 更多