问题
I am trying to get an image that is stored in an array in one screen and set it in as a source for an image in another screen. Essentially when a user touches a certain image that exact image will be carried to the next screen. The problem is that I am receiving an error saying undefined is not an object (evaluating 'navigation.getParam')
the code is as follows: Screen 1
this.state = {
messageItem: null,
chat: [{
convo: [Chat1, Chat2, Pic1, Chat4, Chat5, Chat6],
}]
}
openMessage = (bub) => {
this.setState({
messageItem: bub
});
console.log({ bub })
}
renderChat = () => {
return this.state.chat.map((bub, index) => {
return bub.convo.map((convo, i) => {
if (bub.convo[i])
return (
<Avatar
key={i}
size="medium"
containerStyle={{
marginRight: 15, shadowOpacity: 0.3,
shadowRadius: 2,
shadowColor: 'black'
}}
rounded
source={bub.convo[i]}
onPress={() => { this.openMessage({ convo: bub.convo[i] }) }
} />
)
})
})
}
renderChat = () => {
return this.state.chat.map((bub, index) => {
return bub.convo.map((convo, i) => {
if (bub.convo[i])
return (
<Avatar
key={i}
size="medium"
containerStyle={{
marginRight: 15, shadowOpacity: 0.3,
shadowRadius: 2,
shadowColor: 'black'
}}
rounded
source={bub.convo[i]}
onPress={() => { this.openMessage({ convo: bub.convo[i] }) }
} />
)
})
})
}
render(){
{ this.renderChat() }
{ this.state.messageItem && this.props.navigation.navigate('ChatScreen', { avatarPicture: this.state.messageItem.convo }) }
}
the avatar should be touched which will lead to the ChatScreen, and it's relevant code is as follows:
render() {
const { navigation } = this.props;
<Avatar
size="medium"
containerStyle={{ alignSelf: 'center', position: 'absolute', justifyContent: 'center', marginTop: 28 }}
rounded
source={navigation.getParam('avatarPicture')}
/>
}
回答1:
In Screen1.js
Change below to
onPress={() => { this.openMessage({ convo: bub.convo[i] }) }
openMessage = (bub) => {
this.setState({
messageItem: bub
});
console.log({ bub })
}
to this
onPress={() => { this.openMessage(bub.convo[i]) }
openMessage = (bub) => {
this.setState({
messageItem: bub
});
console.log({ bub })
this.props.navigation.navigate('ChatScreen', { avatarPicture: bub })
}
If your not used the react-redux simply you can access the image like this this.props.navigation.state.params.avatarPicture
If you use react-redux; Bind your navigation params to screens porps like below and then access it using props.
Please remember to import connect
form react-redux
import { connect } from 'react-redux';
ChatScreen.js
const mapStateToProps = (state, props) => {
return {
...props.navigation.state.params
};
};
export default connect(mapStateToProps)(ChatScreen);
And now you will be able access the image like this
this.props.avatarPicture
来源:https://stackoverflow.com/questions/58279318/navigation-getparam-in-not-an-object