问题:如果导航源屏幕的状态更新,有没有办法更新导航目标屏幕中的数据(props(?
比方说,我从ScreenA
导航到ScreenB
并传递它 导航道具data
屏幕A ➔ 屏幕B
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>
)
}
}
附注:
- 我不想使用 Redux 等状态管理。
- 如果我将
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>
)
}
}