类型错误:无法使用 this.props.history.push 读取未定义的属性'push'



我正在学习使用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>
)
}
}

我以前从未这样使用过这个.props.history,我真的不明白它应该如何工作。有人能给我解释一下这里的问题吗?

如果您正在使用React router Dom库进行路由,以下步骤将有所帮助。。

  • 导入"使用路由器";此处为Hoc

即从";react路由器";;

并使用withRouter(component_name(包装您的组件;

请参阅此链接https://reactrouter.com/web/api/withRouter

看起来历史道具丢失了,所以有了上面的更改,应该可以工作了

相关内容

最新更新