javascript - 第一次点击后反应按钮不显示结果,我该如何解决?
问题描述
我有一个反应组件,可以显示数据库中的所有书籍。但是,当我第一次单击该按钮时,它不会列出书籍,但是如果我再次单击该按钮,它将列出所有书籍,我如何仅单击一次就可以列出所有书籍?
import PropTypes from "prop-types";
import {getBook} from "../actions/bookActions";
import {connect} from "react-redux";
import {Container} from "@material-ui/core";
import {Table} from "react-bootstrap";
import {Button} from "react-bootstrap";
const bookList = []
class BookListing extends Component {
constructor(){
super();
this.state= {
id: "",
};
this.onSubmit = this.onSubmit.bind(this);
}
async onSubmit(e){
this.setState({[e.target.name]: e.target.value});
e.preventDefault();
const data = await this.props.getBook();
try {
console.log(data);
bookList.splice(0, bookList.length)
data.forEach(book => {
console.log(book)
bookList.push(book)
})
}catch (exception){
console.log("no books")
}
}
render() {
const { errors } = this.state;
return (
<Container>
<form onSubmit={this.onSubmit}>
<Button variant="dark" type="submit">Show</Button>{' '}
<p>Double click the button</p>
</form>
<h2 color={"green"}>{"\n"}Books found {"\n"}</h2>
<br/>
<br/>
<Table striped bordered hover variant="dark">
<thead>
<tr>
<th>Book Id</th>
<th>Title</th>
<th>Author</th>
<th>Category</th>
</tr>
</thead>
<tbody>
{bookList.map((book => <tr>
<td>{book.id}</td>
<td>{book.title}</td>
<td>{book.author}</td>
<td>{book.category}</td>
</tr>))}
</tbody>
</Table>
</Container>
)
}
}
BookListing.propTypes = {
createProject: PropTypes.func.isRequired
};
export default connect(null, {getBook})(BookListing);
解决方案
由于您需要对 的更改做出反应bookList
,因此它需要成为状态的一部分。
this.state = {id:'', bookList: [] }
用来自 的书籍onSubmit
替换。bookList
data
// slice without arguments clones an array
this.setState({bookList: data.slice()});
在 React 中更新状态数组时,应该使用concat
, slice
, filter
,map
而concat
不是push
,splice
等[]
。前者返回一个新数组。后者修改现有的状态数组,可能会被react忽略。有关更多详细信息,请参阅本文。
上面代码中的切片,可能不是真的需要。(仅用于演示。)
最后,在渲染<tr>
s 列表时,您需要为每个 s 指定一个唯一键<tr>
。您可以book.id
用作键。
<tr key={book.id}>
推荐阅读
- flutter - 秒表不会减少时间
- c# - 将泛型列表声明为父类的成员
- javascript - 获取要在 if 语句中使用的循环中的项目索引以获取另一个对象中的值
- flutter - Flutter Widget 构建和结构
- r - 如何更改ggplot饼图上的图例值?
- c# - Selenium C# 使用 XPath 或 CssSelector 查找属性和 CSS 类
- unicode - 如何在文本中查找 unicode 字符?
- c# - 如何使用张量流模型对图像进行单一预测?
- jquery - 如何计算属性产品的总和 [Laravel]
- java - 使用文件观察器检测远程 Linux 服务器上的更改