如何在 react-native 中使用 StackNavigator 的组件中获取数据?
How to fetch data in a component which is using StackNavigator in react-native?
这是我尝试使用 react-native -
为 iOS 应用程序做的事情
- 我正在使用 StackNavigator
- 在主屏幕中,我显示了
AysncStorage
中的 get/fetch
列表中的所有项目。这是在 componentDidMount()
中完成的。这很好用。
- 我转到下一个屏幕(使用 StackNavigator)以将新项目添加到 AsyncStorage 的列表中。项目已添加。
- 当我使用后退按钮返回主屏幕时,未显示更新的列表。此外,
componentDidMount()
未被调用。
如何解决这个问题?
Redux 是最好的选择,但以下是一个肮脏的解决方法:
主屏幕
state = { items: [] }
addItemFromChild = (item) => {
this.setState((prevState) => ({ items: [...prevState.items, item] }))
}
goToAddItemScreen = () => {
this.props.navigation.dispatch(NavigationActions.navigate({ routeName: "AddItemScreen", params: { addItemFromChild: this.addItemFromChild } }))
}
添加项目屏幕
addItem = (item) => {
this.props.navigation.state.params.addItemFromChild(item)
}
这是我尝试使用 react-native -
为 iOS 应用程序做的事情- 我正在使用 StackNavigator
- 在主屏幕中,我显示了
AysncStorage
中的get/fetch
列表中的所有项目。这是在componentDidMount()
中完成的。这很好用。 - 我转到下一个屏幕(使用 StackNavigator)以将新项目添加到 AsyncStorage 的列表中。项目已添加。
- 当我使用后退按钮返回主屏幕时,未显示更新的列表。此外,
componentDidMount()
未被调用。
如何解决这个问题?
Redux 是最好的选择,但以下是一个肮脏的解决方法:
主屏幕
state = { items: [] }
addItemFromChild = (item) => {
this.setState((prevState) => ({ items: [...prevState.items, item] }))
}
goToAddItemScreen = () => {
this.props.navigation.dispatch(NavigationActions.navigate({ routeName: "AddItemScreen", params: { addItemFromChild: this.addItemFromChild } }))
}
添加项目屏幕
addItem = (item) => {
this.props.navigation.state.params.addItemFromChild(item)
}