问题:如果“导航源”屏幕的状态已更新,是否可以在“导航目标”屏幕中更新数据(属性)?
让我从ScreenA
导航到ScreenB
,然后将其传递给导航道具data
ScreenA➔ScreenB
ScreenA {
navigate('ScreenB', {data: this.state.data})
someEvent(){
this.setState({data: newData})
}
}
显示ScreenB
时,ScreenA
上发生了一些事件,并且其state.data
被更新。 ScreenB
如何获取此更新的数据?
我将尝试用详细的代码示例来进一步说明:
有一个PostInfo
类屏幕,该屏幕将所有评论存储在帖子中,并呈现一个按钮。单击此按钮后,屏幕导航到PostDetails
类屏幕。 PostInfo
类提供allComments
和回调函数replyCommentCB
作为导航道具。
然后,此PostDetails
类呈现所有评论和评论回复textInputBox
。当用户通过此textInputBox
回复评论时,将触发回调函数replyCommentCB
,并通过添加此新评论来更新PostInfo
类中的状态。
但是,现在我也希望allComments
的新更新状态也反映在PostDetails
屏幕中,以便也可以呈现此新添加的注释。
class PostInfo {
constructor(props) {
this.state = {
allComments = []
}
}
replyCommentCB = (text) => {
/* Update comment in DataBase first then update state */
updatedAllComments = this.state.allComments
updatedAllComments.push(text)
this.setState ( {
allComments : updatedAllComments
})
}
onButtonPress = () => {
this.navigation.navigate('PostDetails', {
allComments : this.state.allComments,
replyCommentCB: this.replyCommentCB,
}
);
}
render () {
return (
<Button title={"Show Comments"} onPress={this.onButtonPress}/>
)
}
}
class PostDetails {
render() {
let allComments = this.props.navigation.getParam('allComments',[]);
let replyCommentCB = this.props.navigation.getParam('replyCommentCB','');
return (
<ScrollView>
/* Render "allComments" here */
<TextInputBox onSubmit={replyCommentCB} />
</ScrollView>
)
}
}
PS:
PostDetails
类放在一个模式中(而不是navigation.navigate),工作正常。 (在PostInfo类中更新状态时,也会更新PostDetails
模态的道具)我自己做的。我需要做的就是从函数回调返回更新的数据。
class PostInfo {
constructor(props) {
this.state = {
allComments = []
}
}
replyCommentCB = (text) => {
/* Update comment in DataBase first then update state */
updatedAllComments = this.state.allComments
updatedAllComments.push(text)
this.setState ({ allComments : updatedAllComments })
return updatedAllComments; // return the data that you want to get updated in navigated screen
}
onButtonPress = () => {
this.navigation.navigate('PostDetails', {
allComments : this.state.allComments,
replyCommentCB: this.replyCommentCB,
}
);
}
render () {
return (
<Button title={"Show Comments"} onPress={this.onButtonPress}/>
)
}
}
class PostDetails {
constructor(props) {
super(props)
this.replyCommentCB = this.props.navigation.getParam('replyCommentCB','');
this.state = { allComments : this.props.navigation.getParam('allComments',[]) }
}
onReplyComment(text) {
const updatedAllComments = this.replyCommentCB(text)
this.setState({ allComments : updatedAllComments })
}
render() {
return (
<ScrollView>
/* Render "this.state.allComments" here */
<TextInputBox onSubmit={onReplyComment} />
</ScrollView>
)
}
}