我在网上看到一些教程,大多数示例都在使用
类组件,例如
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
所以在我的第二个代码片段中,如何调用 getData 以便我在 NewComponent 中显示数据?
您有多种选择。就个人而言,我会选择#3
-
你可以让你的子组件成为一个类,并使用 React 的生命周期方法,例如
componentDidMount
-
您可以将
getData
函数移动到另一个 JavaScript 模块。然后从父组件导入并调用它。将结果作为道具向下传递到子组件中。 -
使用 React 的效果钩子。另请注意通过跳过效果优化性能部分。
希望有帮助。