我创建了一个反应示例应用程序,但我觉得这在编码标准方面做得不是很好,我是新的反应,请指出我可以使代码高效的地方。我想知道编码标准也可以使用。 我项目中的示例方法显示在
下面componentWillMount(){
axios.get('http://localhost:8095/books')
.then(res=>{
const books=res.data;
this.setState({books});
});
axios.get('http://localhost:8095/authors')
.then(res=>{
const authors=res.data;
this.setState({authors});
})
}
onAdd(Name,ISBN,Author,Price,Year,Publisher){
const books=this.getBooks();
books.push({
Name,
ISBN,
Author,
Price,
Year,
Publisher
});
this.setState({books});
axios.post(`http://localhost:8095/books`, {
Name:Name,
ISBN:ISBN,
Author:Author,
Price:Price,
Year:Year,
Publisher:Publisher
}).then(res => {
console.log(res);
console.log(res.data);
})
}
onDelete(Name){
const books=this.getBooks();
const filteredproducts=books.filter(book=>{
return book.Name !==Name;
});
this.setState({books:filteredproducts})
console.log(filteredproducts);
axios.delete(`http://localhost:8095/books/${Name}`).then(res => {
console.log(res);
console.log(res.data);
})
}
提前谢谢
答案 0 :(得分:0)
我稍微修改了你的代码。 您可以使用component did mount进行初始数据调用,从而提高性能。 Performing multiple concurrent requests
componentDidMount(){
//Performing multiple concurrent requests and avoid multipletimes setState
axios.all([axios.get('http://localhost:8095/books'), axios.get('http://localhost:8095/authors')])
.then(axios.spread(function (books, authors) {
this.setState({
books,
authors
});
}));
}
onAdd(Name,ISBN,Author,Price,Year,Publisher){
// you can pass this args as object and directly push object in books
const books=this.getBooks();
books.push({
Name,
ISBN,
Author,
Price,
Year,
Publisher
});
// you should use setState callback
this.setState({books}, () => {
axios.post(`http://localhost:8095/books`, {
Name:Name,
ISBN:ISBN,
Author:Author,
Price:Price,
Year:Year,
Publisher:Publisher
}).then(res => {
console.log(res);
console.log(res.data);
})
});
}
onDelete(Name){
const books=this.getBooks();
const filteredproducts = books.filter(book => book.Name !== Name); // you can use single line functions in this case
this.setState({books:filteredproducts})
console.log(filteredproducts);
axios.delete(`http://localhost:8095/books/${Name}`).then(res => {
console.log(res);
console.log(res.data);
})
}