【问题标题】:how to call fetch in a sub component in react native?react native 如何在子组件中调用 fetch?
【发布时间】:2019-09-04 17:24:23
【问题描述】:

我在网上看到了一些教程,大部分示例都在使用

一个类组件,例如

export default class App extends Component {

      constructor() {
        super();
        //set state here and data source 
      } 

      componentDidMount() {
        //get json data here
      }

     render() {
       return(
          blah blah blah
       )
     }

}

如果我想让一个子组件有一个调用 fetch 的功能怎么办?

    //NewComponent.js
    //this is my sub component
    const NewComponent = () => {
        return(
          <FlatList />
          //I want a list of data here
        )
    }

   const getData = () => {
     //call fetch here
   }

   export default NewComponent

那么在我的第二个代码 sn-p 中,如何调用 getData 以便我在 NewComponent 中显示数据?

【问题讨论】:

    标签: react-native react-native-android react-native-ios react-native-flatlist


    【解决方案1】:

    您有多种选择。我个人会选择#3

    1. 你可以让你的子组件成为一个类,并使用 React 的生命周期方法,例如 componentDidMount

    2. 您可以将getData 函数移动到另一个javascript 模块。然后从父组件导入并调用它。将结果作为 props 传递到子组件中。

    3. 使用 React 的 Effect Hook。也关注Optimizing Performance by Skipping Effects部分。

    希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-27
      • 2016-11-13
      相关资源
      最近更新 更多