我有一个带有本地App.js的react-native应用程序:

import { createStackNavigator } from 'react-navigation';

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

export withAuth(App)

高阶组件withAuthuserauthenticating Prop 添加到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传递给AppContainerProfile

因此,user中的authenticatingAppContainer Prop 是未定义的。
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中的componentDidMount属性,而只能读取render() { ... }中的属性。

理想情况下,我想从user传递authenticatingAppStack属性,我该怎么做?

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

最佳答案

您可以通过screenProps将 Prop 从高级组件传递到子屏幕。例:

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


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

09-25 16:14