TypeError:undefined不是对象(评估'_this2.props.navigation.navigate')

时间:2020-09-11 11:44:32

标签: javascript react-native react-navigation

我已经阅读了本机导航文档,但找不到任何解决方案

我想使用孩子们来发送道具,但导航时(onPress)出现此错误

album.js

const StackAlbum = createStackNavigator()

class Album extends Component {
    constructor(props) {
        super(props)
        this.state = {
            albums: [],
            photo: []
        }
    }

componentDidMount() {
    // Get data from link then set state
    fetch("https://jsonplaceholder.typicode.com/albums")
        .then(res => res.json())
        .then(jsonRes => this.setState({
            albums: jsonRes
        }))
        .catch(err => console.log(err))

}

render() {
    return (
        <StackAlbum.Navigator
            initialRouteName="AlbumScreen"
        >
            <StackAlbum.Screen
                name="AlbumScreen"                    
                children={() => <AlbumScreen
                                    albums={this.state.albums} //HERE WE GO
                                />}               
            />
            <StackAlbum.Screen
                name="PhotoScreen"
                component={PhotoScreen} 
                options={{
                    headerShown: true
                }}               
            />
        </StackAlbum.Navigator>
    )
    }
}

export default Album

albumScreen.js

render() {
    return (
        <ScrollView>
            <Text>Albums</Text>
            <TouchableOpacity
                style={styles.button}
                onPress={() => this.props.navigation.navigate("PhotoScreen")} // HERE IS THE ERROR
            >
                <Text>Go To Photo</Text>
            </TouchableOpacity>
            <View>
                {this.showAlbum()}
            </View>                
        </ScrollView>
    )
}

我尝试使用 component = {AlbumScreen} 但困惑地发送道具。有人有解决方案吗?

1 个答案:

答案 0 :(得分:0)

以下是将道具从导航器传递到屏幕的方法:

<StackAlbum.Screen name="AlbumScreen">
  {props => <AlbumScreen{...props} albums={this.state.albums} />}
</StackAlbum.Screen>