无法从反应导航中找到参数
Can't find params from react-navigation
我有一个非常困惑的问题。我使用 react-navigation 在我的 react-native 应用程序上导航。
navigate('Story', { id: story.id })
此代码有效,并为我提供了一个可以在 StoryScreen 上使用的 ID
navigate('User', { id: user.id })
但是这段代码没有给我一个我可以在我的 UserScreen 上使用的 ID,我已经测试过发送一个整数但它没有注册。
Link 编码:https://github.com/yarism/StoryWarsApp/blob/master/app/screens/navigation/NavigationScreen.js
用户界面:
import React from 'react';
import {
AppRegistry,
Text,
View,
ScrollView,
Image,
StyleSheet
} from 'react-native';
export default class UserScreen extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.setState({ isLoading: true });
this.fetchUser();
}
fetchUser() {
fetch('https://www.storywars.net/api/users/' + this.props.navigation.state.params.id)
this.props.navigation.state.params.id 未定义
检查您的存储库后,我认为错误出在 App.js
中 TabNav 中的 UserScreen
。
默认情况下,Tabview 最初是一起加载的。那时,状态中没有params.id
。解决这个问题的一种方法是以某种方式为用户 ID 设置一个默认值。目前无法为场景设置默认参数,但您可以使用 screenProps
从导航器中传递一些东西。
例如
const Navigator = TabNavigator({...});
return <Navigator screenProps={{ userId: 2, ...this.props.screenProps }} />
然后想办法区分个人资料页面与常规 UserScreen,使用 this.props.screenProps.userId
获取个人资料页面。
我有一个非常困惑的问题。我使用 react-navigation 在我的 react-native 应用程序上导航。
navigate('Story', { id: story.id })
此代码有效,并为我提供了一个可以在 StoryScreen 上使用的 ID
navigate('User', { id: user.id })
但是这段代码没有给我一个我可以在我的 UserScreen 上使用的 ID,我已经测试过发送一个整数但它没有注册。
Link 编码:https://github.com/yarism/StoryWarsApp/blob/master/app/screens/navigation/NavigationScreen.js
用户界面:
import React from 'react';
import {
AppRegistry,
Text,
View,
ScrollView,
Image,
StyleSheet
} from 'react-native';
export default class UserScreen extends React.Component {
constructor(props) {
super(props);
}
componentWillMount() {
this.setState({ isLoading: true });
this.fetchUser();
}
fetchUser() {
fetch('https://www.storywars.net/api/users/' + this.props.navigation.state.params.id)
this.props.navigation.state.params.id 未定义
检查您的存储库后,我认为错误出在 App.js
中 TabNav 中的 UserScreen
。
默认情况下,Tabview 最初是一起加载的。那时,状态中没有params.id
。解决这个问题的一种方法是以某种方式为用户 ID 设置一个默认值。目前无法为场景设置默认参数,但您可以使用 screenProps
从导航器中传递一些东西。
例如
const Navigator = TabNavigator({...});
return <Navigator screenProps={{ userId: 2, ...this.props.screenProps }} />
然后想办法区分个人资料页面与常规 UserScreen,使用 this.props.screenProps.userId
获取个人资料页面。