我有这个功能组件。
import { useHistory } from "react-router-dom";
function ProfileForm(props) {
const form = useForm();
const {
register,
handleSubmit,
errors
} = form;
const history = useHistory(); // TypeError: Cannot read property 'history' of undefined
......
}
为什么会出现此错误?顺便说一句,我安装了react-router-dom。如何在功能组件中使用历史记录?
更新更多代码:-
axios.post('http://localhost:8080/profile', profile)
.then(res => {
history.push({
pathname: "/OnSubmit",
state: {
response: res.data,
msgVariant: "success"
}
})
}).catch((error) => {
// handle this error
history.push({
pathname: "/OnSubmit",
state: {
response: error.message,
msgVariant: "danger"
}
})
})
以后我正在使用上述历史记录吗?
答案 0 :(得分:2)
无论是功能组件还是类组件,要使路由器历史记录起作用,该组件必须是路由器组件的子代。
我们需要做这样的事情,
import {
BrowserRouter as Router
} from "react-router-dom"
//and then, wherever we want to use `history`, we need to have it nested under this <Router />
<Router>
<SomeOtherComponent>
...
<ComponentWhereWeWantToUseHistory />
...
</SomeOtherComponent>
</Router>
我希望它会有所帮助。编码愉快:)