通过由createStackNavigator`构建的导航容器来响应Native pass`props'

时间:2018-07-22 17:09:31

标签: javascript react-native react-router react-navigation

我有一个顶级App.js的React-native应用程序:

import { createStackNavigator } from 'react-navigation';

class App extends Component {
  render() { 
    return <AppStack {..this.props} /> 
  }
}

export withAuth(App)

高阶元素withAuthuser上添加authenticatingApp道具:

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 AppAppContainer的{​​{1}}传递。

因此Profile中的userauthenticating道具是未定义的。

AppContainer

我可以将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 包裹在AppContainer内并做withAuth,但随后export default withAuth(AppContainer)无法读取AppContainer中的this.props.user属性,只能读取{ {1}}。

理想情况下,我想从componentDidMount传递render() { ... }user属性,我该怎么做?

注意:目前,我尽可能不使用authenticating。这是一个简单的应用程序。

1 个答案:

答案 0 :(得分:1)

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

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

检查Navigator Props以获得更多详细信息。