如何在react-native中使用StackNavigator的组件中获取数据?

时间:2021-04-18 18:58:39

Here is what I am trying to do for an iOS app using react-native -

以下是我尝试使用react-native为iOS应用程序做的事情 -

  1. I am using StackNavigator
  2. 我正在使用StackNavigator
  3. In the home screen, I show all the items in a list which is get/fetch from AysncStorage. This is done in the componentDidMount(). This works fine.
  4. 在主屏幕中,我显示列表中的所有项目,这些项目是从AysncStorage获取/获取的。这是在componentDidMount()中完成的。这很好用。
  5. I go to a next screen (using StackNavigator) to add a new item to the list in the AsyncStorage. Item is added.
  6. 我转到下一个屏幕(使用StackNavigator)将新项添加到AsyncStorage的列表中。项目已添加。
  7. When I come back to the home screen using the back button, the updated list is not shown. Also, the componentDidMount() is not called.
  8. 当我使用后退按钮返回主屏幕时,不会显示更新的列表。此外,不调用componentDidMount()。

How can this issue be solved?

如何解决这个问题?

1 个解决方案

#1


0  

Redux is the best option but a dirty workaround is the following:

Redux是最好的选择,但是一个肮脏的解决方法如下:

Home screen

主屏幕

state = { items: [] }

addItemFromChild = (item) => {
   this.setState((prevState) => ({ items: [...prevState.items, item] }))
}

goToAddItemScreen = () => {
   this.props.navigation.dispatch(NavigationActions.navigate({ routeName: "AddItemScreen", params: { addItemFromChild: this.addItemFromChild } }))
}

AddItemScreen

AddItemScreen

addItem = (item) => {
   this.props.navigation.state.params.addItemFromChild(item)
}

#1


0  

Redux is the best option but a dirty workaround is the following:

Redux是最好的选择,但是一个肮脏的解决方法如下:

Home screen

主屏幕

state = { items: [] }

addItemFromChild = (item) => {
   this.setState((prevState) => ({ items: [...prevState.items, item] }))
}

goToAddItemScreen = () => {
   this.props.navigation.dispatch(NavigationActions.navigate({ routeName: "AddItemScreen", params: { addItemFromChild: this.addItemFromChild } }))
}

AddItemScreen

AddItemScreen

addItem = (item) => {
   this.props.navigation.state.params.addItemFromChild(item)
}