chi*_*ro2 3 javascript react-router react-native react-navigation
我有一个顶级的本机应用程序,App.js它是:
import { createStackNavigator } from 'react-navigation';
class App extends Component {
render() {
return <AppStack {..this.props} />
}
}
export withAuth(App)
Run Code Online (Sandbox Code Playgroud)
高阶组件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} />)
}
}
Run Code Online (Sandbox Code Playgroud)
这AppStack是:
const AppStack = createStackNavigator(
{ AppContainer, Profile },
{ initialRouteName : 'AppContainer' }
)
Run Code Online (Sandbox Code Playgroud)
请注意,没有代码传递props从class Appdown传递到AppContainer和 的Profile。
因此user,authenticating里面的和道具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
Run Code Online (Sandbox Code Playgroud)
我可以AppContainer在里面换行withAuth并执行export default withAuth(AppContainer),但随后AppContainer无法读取 中的this.props.user属性componentDidMount,只能在render() { ... }.
理想情况下,我想从 传递user和authenticating财产AppStack,我该怎么做?
注意:redux如果可能的话,现在我不想使用。这是一个简单的应用程序。
您可以通过screenProps. 例子:
const withTest = Component => (
class WithTest extends React.Component {
render() {
return (<Component screenProps={{ user: "abc" }} />);
}
});Run Code Online (Sandbox Code Playgroud)
查看导航器道具以获取更多详细信息。
| 归档时间: |
|
| 查看次数: |
5343 次 |
| 最近记录: |