【发布时间】:2018-08-15 07:30:34
【问题描述】:
我正在使用this API 创建一个hackernews-clone
这是我的组件结构
-main
|--menubar
|--articles
|--searchbar
下面是我用来从外部 API 获取数据的代码块。
componentWillReceiveProps({search}){
console.log(search);
}
componentDidMount() {
this.fetchdata('story');
}
fetchdata(type = '', search_tag = ''){
var url = 'https://hn.algolia.com/api/v1/search?tags=';
fetch(`${url}${type}&query=${search_tag}`)
.then(res => res.json())
.then(data => {
this.props.getData(data.hits);
});
}
我正在componentDidMount() 生命周期方法(应该如此)中进行 API 调用,并在启动时正确获取数据。
但是这里我需要通过 searchbar 组件将搜索值传递给 menubar 组件来进行自定义搜索。因为我只使用 react(不使用 redux atm),所以我将它作为 prop 传递给 menubar 组件。
正如提到的代码块,如果我搜索 react 并通过 props 传递它,它会记录一次 react(我在 componentWillReceiveProps() 上调用它)。但是,如果我在 componentWillReceiveProps 中使用 search 参数运行 fetchData 方法,我会收到一个无限循环。甚至在我将搜索值作为道具传递之前,它就进入了无限循环。
那么在这里,我如何调用fetchdata() 方法来更新props ?
我已经阅读了this stackoverflow 的答案,但是在componentWillReceiveProps 中进行 API 调用不起作用。
那么我应该在哪里打电话给fetchdata()?这是因为异步吗?
更新:项目的codepen
【问题讨论】:
标签: javascript reactjs react-props