【发布时间】:2020-12-07 11:59:55
【问题描述】:
我正在学习使用 Axios 使用 React 更新项目的课程。我正在按照步骤操作,但遇到了功能问题。当我单击更新按钮时,它应该将我重定向到预先填充了项目表单的页面,但出现错误:TypeError: Cannot read property 'push' of undefined
请参阅下面的代码以及问题所在的 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 之类的东西进行路由?
-
是的,你要我添加那个组件代码吗?
-
我可能会根据您使用的 react 路由器版本与课程中的版本有些不匹配。看看这是否有帮助stackoverflow.com/questions/44312437/…
-
我可能在你的链接中找到了一些东西,谢谢
-
您可以尝试加载具有历史记录的子组件。为此,请通过道具传递“历史”。类似的东西:return ()
标签: javascript reactjs axios event-handling crud