我是新来的人,我正在研究搜索属性。当我尝试过滤状态组件时,我正在从状态组件获取值,这将引发以下错误。 “ TypeError:无法读取null的属性'value'”
return (
<div>
<Form>
<Row>
<Col sm={10}>
<FormControl type="text" placeholder="Search" value = {this.state.Searchvalue} onChange = {e => this.setState(prevState => ({
SearchBooks: prevState.SearchBooks.filter(book => book.title === e.target.value)
}))} />
</Col>
<Col sm={2}>
<Button variant="outline-success">Search</Button>
</Col>
</Row>
</Form>
<br/>
{this.state.SearchBooks.map(book => (
<div>
<Card key = {book.id}>
<Card.Header as="h5">{book.bookname}</Card.Header>
<Card.Body>
<Card.Title>{book.title}</Card.Title>
<Card.Text>
Author : {book.authorname}<br/>
Email id : {book.aemailid}<br/>
ISBN : {book.isbn}<br/>
</Card.Text>
<Button variant="danger" onClick={ () => this.removeBook(book.id)}>Delete Book</Button>
<Button variant="primary" onClick={() => this.flagedit(true,book)}>Edit Book</Button>
{/* <Button variant="primary" onClick={() => this.editmodal(book.bookname)}>Edit Book</Button> */}
{this.editmodal()}
</Card.Body>
<Card.Footer className="text-muted">count : {book.count}</Card.Footer>
</Card>
<br/>
</div>
))}
</div>
)
}
答案 0 :(得分:0)
由于性能问题,请对重用事件对象做出反应,并将它们在不同事件之间设置为null。因此,在执行stateUpdated函数时,event的值为null,因此尝试读取null.value会抛出“ TypeError:无法读取null的属性'value'”
要解决此问题,您可以执行以下操作
<FormControl
type="text"
placeholder="Search"
value={this.state.Searchvalue}
onChange={e => {
const currentValue = e.target.value;
this.setState(prevState => ({
SearchBooks: prevState.SearchBooks.filter(
book => book.title === currentValue
),
}));
}}
/>;
答案 1 :(得分:0)
问题是因为您在e.target.value
内使用setState()
。
影响此的两个因素:
由于onChange
是Synthetic Event
,因此在调用后将被重用。因此,e
在onChange
setState()
是异步的。
因此,您可以:
1。声明一个变量:
onChange = (e) => {
const eventValue = e.target.value // declare a variable
this.setState(prevState => ({
SearchBooks: prevState.SearchBooks.filter(book => book.title === eventValue)
})
}
<FormControl type="text"
onChange={onChange}
/>
或
2。通过event.persist()
onChange = (e) => {
e.persist() // persist event
this.setState(prevState => ({
SearchBooks: prevState.SearchBooks.filter(book =>
book.title === event.target.value
)
})
}