[英]TypeError: Cannot read property 'push' of undefined with this.props.history.push
I'm following a course to update an item with React using Axios. I'm following the steps but I meet a problem with a function. When I click on the update button, it should redirect me to a page with the item form prepopulated but I got an error: TypeError: Cannot read property 'push' of undefined我正在学习使用 Axios 使用 React 更新项目的课程。我正在执行这些步骤,但我遇到了 function 的问题。当我单击更新按钮时,它应该将我重定向到一个预填充了项目表单的页面但我收到一个错误:TypeError: Cannot read property 'push' of undefined
See my code bellow with the handleUpdate function where the problem come from:请参阅下面的 handleUpdate function 问题所在的代码:
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>
)
}
}
I have never used this.props.history that way before and I don't really understand how it should work.我以前从未以这种方式使用过 this.props.history 并且我真的不明白它应该如何工作。 Does anyone can explain me the problem here?
有谁能在这里解释我的问题吗?
If you are using React-router Dom library for Routing below steps would help..如果您使用 React-router Dom 库进行路由,则以下步骤会有所帮助。
ie import { withRouter } from "react-router";即从“react-router”导入{withRouter};
and wrap your component with withRouter(component_name);并用 withRouter(component_name); 包裹你的组件
Plz refer this link https://reactrouter.com/web/api/withRouter请参考此链接https://reactrouter.com/web/api/withRouter
looks like history props is missing so with above changes this should work看起来 history props 丢失了所以通过上面的更改这应该可以工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.