问题描述
我正在按照课程使用Axios使用React更新项目。我正在按照步骤操作,但是遇到函数问题。当我单击“更新”按钮时,它应将我重定向到预填充项目表单的页面,但出现错误:TypeError:无法读取未定义的属性“ push”
请参阅我的代码,其中包含来自问题的handleUpdate函数:
export default class ListBooks extends React.Component {
constructor(props) {
super(props);
this.state = { error: null,data: [],number: "",name: "" }
}
componentDidMount() {
Axios.get(process.env.REACT_APP_API_PATH_BOOKS)
.then(res => {
this.setState({ data: res.data });
})
.catch(errorThrown => {
this.setState({ error: errorThrown });
})
}
/**
* Use to delete a book by the number.
*/
handleDelete = (index) => {
const id = this.state.data[index].name
Axios.delete(process.env.REACT_APP_API_PATH_BOOKS + id)
.then(res => {
console.log(res);
console.log(res.data);
this.setState(prevstate => ({ ...prevstate,data: prevstate.data.filter((book) => book.name !== id) }))
})
.catch(errorThrown => {
this.setState({ error: errorThrown });
})
}
handleUpdate = event => {
event.preventDefault();
this.props.history.push(`/admin/${this.state.number}/edit`);
console.log(this.props);
}
render() {
const { data } = this.state;
return (
<div>
<Container>
{data.map((books,index) =>
<div key={books.number}>
<ListGroup>
<ListGroup.Item disabled id={"book-admin" + data[index].number}>{books.number}. {books.name} {books.author}
</ListGroup.Item>
</ListGroup>
<Button variant="outline-warning" size="sm" className="btn-admin-change" onClick={this.handleUpdate}>Modifier</Button>
<Button variant="outline-danger" size="sm" className="btn-admin-change" onClick={() => this.handleDelete(index)}>Supprimer</Button>
</div>
)}
</Container>
</div>
)
}
}
我以前从未以这种方式使用过this.props.history,而且我不太了解它应该如何工作。有人可以在这里向我解释问题吗?
解决方法
如果您将React-router Dom库用于路由,则以下步骤将有所帮助。
- 在此处导入“ withRouter” Hoc
即从“反应路由器”中导入{withRouter};
并使用withRouter(component_name);包装您的组件;
请点击此链接https://reactrouter.com/web/api/withRouter
看起来好像缺少历史道具,因此通过上述更改,它应该可以工作