[英]Axios.get() ReactJS
我正在 ReactJS 中制作简单的待办事项应用程序。现在我正在添加我设法实现.post
方法的路线,但现在我被困在.get
方法上,它正在循环并一遍又一遍地渲染。 这就是我在做什么。
state = {
inputValue: '',
todos: [],
currentPage: 1,
pageCount: 1,
itemsPerPage: 10,
};
getAll = () => {
let {todos} = this.state
axios
.get("http://localhost:8080/", {
todos:todos
})
.then((res) => {
this.setState({todos:res.data})
})
.catch((err) => {
console.log("err", err);
});
};
render() {
const {itemsPerPage, currentPage, todos} = this.state;
const end = currentPage * itemsPerPage
const start = end - itemsPerPage
const currentItems = todos.slice(start, end);
return <div className={"App"}>
<div className="App-header">
<h2>Welcome to To-Do List App</h2>
</div>
<input ref={this.inpRef} onKeyPress={this.handleKeyPress} name={''} type='text'/>
<button onClick={() => this.addItem()} className={'btn btn-primary'}>Add</button>
<ul>
{
todos.length ?
currentItems.map(todoItem => <ListItem
key={todoItem.id}
todoItem={todoItem}
deleteItem={this.deleteItem}
editItem={this.editItem}
submitEdit={this.submitEdit}
getAll = {this.getAll}
/>) :
null
}
<div>
{this.getAll()}
{this.renderPagination()}
</div>
</ul>
</div>
};
}
export default App;
我要做的就是将接收到的数据渲染到<ul>
并使其显示为li
,但问题是它陷入了无限循环并且一遍又一遍地更新页面。 有什么建议么?
对您来说,上面的代码导致了一个问题,因为在上面的代码中,我们没有正确使用反应生命周期钩子,并在渲染 function 中调用 HTTP。 因为这是基于类的组件。 您可以尝试使用 componentDidMount() 生命周期挂钩在组件加载之前进行所有 HTTP 调用,并在组件更新后使用 componentUpdateMount() 生命周期挂钩。
如果你在 react 中使用功能组件而不是在 react 16 及更高版本中,我们现在有 react-hooks,这些反应钩子帮助我们在 useEffect() 钩子中制作相同的 HTTP。 您也可以从 react 官方网站进一步了解它。 我希望它会有所帮助:) https://reactjs.org/docs/react-component.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.