代码之家  ›  专栏  ›  技术社区  ›  xiaolingxiao

通过由“createStackNavigator”生成的导航容器响应本机传递“props”`

  •  1
  • xiaolingxiao  · 技术社区  · 8 年前

    我有一个顶级的react本地应用程序 App.js 即:

    import { createStackNavigator } from 'react-navigation';
    
    class App extends Component {
      render() { 
        return <AppStack {..this.props} /> 
      }
    }
    
    export withAuth(App)
    

    其中高阶分量 withAuth 添加 user authenticating 道具 App :

    const withAuth = (Component) =>
      class WithAuth extends React.Component {
        constructor(props) {
          super(props)
          this.state = {
            authenticating: true,
            user: false
          }
        }
    
        componentDidMount() {
          // authenticating logic ...
          firebase.auth().onAuthStateChanged(user => {
            if (user)
              this.setState({
                authenticating: false,
                user: user
              })
            else
              this.setState({
                authenticating: false
              })
          })
        }
    
        render() {
          return (<Component user={this.state.user} authenticating={this.state.authenticating} {...this.props} />)
        }
      }
    

    以及 AppStack 是:

    const AppStack = createStackNavigator( 
        { AppContainer, Profile }, 
        { initialRouteName : 'AppContainer' }
    )
    

    注意没有代码通过 props 那是从 class App 下降到 AppContainer Profile .

    因此 用户 认证 里面的道具 应用程序容器 未定义。

    class AppContainer extends Component {
      //  this.props.user is false and this.props.authenticating is true
      componentDidMount() {
        console.log(`Debug Did mount with user: ${this.props.user}`, this.props.authenticating)
      }
    
      render() {
        // if I `export withAuth(AppContainer)`, then this prints the user information. but not if I log inside `componentDidMount`
        console.log(`Debug loaded with user: ${this.props.user}`, this.props.authenticating)
        return <Text>'hello world'</Text>
      }
    }
    
    export default AppContainer
    

    我可以包起来 应用程序容器 里面 带授权 并且做 export default withAuth(AppContainer) ,但是 应用程序容器 无法读取 this.props.user 财产 componentDidMount ,仅在 render() { ... } .

    理想情况下我想把 用户 认证 财产来源 应用程序堆栈 ,我该怎么做?

    注:目前我不想使用 redux 如果可能的话这是一个简单的应用程序。

    1 回复  |  直到 8 年前
        1
  •  4
  •   tuan.tran    8 年前

    您可以将道具从高阶组件传递到子屏幕 screenProps . 例子:

    const withTest = Component => (
      class WithTest extends React.Component {
        render() {
          return (<Component screenProps={{ user: "abc" }} />);
        }
      });

    支票 Navigator Props 更多细节。

    推荐文章