我被困住了。请求后,我无法重定向用户。
有我的要求(在组件中):
const onSubmit = (data) =>{
const datafull =
{
"title": data.title,
"excerpt": "nonex5",
"content": data.content,
"location": data.location,
"company_id": "75",
"category_id": data.category_id,
"date_start_at": data.date_start_at,
"date_end_at": data.date_end_at,
"link" : data.link,
}
console.log(datafull);
axios({
method: 'post',
url: 'url',
data: datafull,
})
.then(function (res) {
{
console.log('resolution',res.data);
return <Redirect to="/company/news" />
};
})
.catch(function (erreur) {
console.log(erreur);
});};
const { register, handleSubmit, errors } = useForm();
有人建议帮助我解决问题吗?
答案 0 :(得分:0)
您可以使用路线道具中的历史记录。
import { useHistory } from "react-router-dom";
const history = useHistory();
history.replace("/company/news"); or history.push("/company/news");
我希望您觉得它有用
答案 1 :(得分:0)
您可以使用历史记录挂钩从一条路线转到另一条路线
import { useHistory } from 'react-router-dom';
const YourComponent = () => {
const history = useHistory();
// trigger this method to go to news page
function goToNews() {
history.push('/company/news');
}
}
或者您也可以使用window对象-
window.location.replace("url")
//or
window.location.assign("url")
答案 2 :(得分:0)
T!问题已解决:
axios({
method: 'post',
url: 'url',
data: datafull,
})
.then(function (res) {
{
console.log('resolution',res.data);
return history.push("/company/news");
};
})
.catch(function (erreur) {
console.log(erreur);
});};
谢谢!
答案 3 :(得分:0)
尝试此解决方案:
import React, { useState } from "react";
import axios from "axios";
import { useForm } from "react-hook-form";
import { Redirect } from "react-router-dom";
function ResponseHandler() {
const { register, handleSubmit, errors } = useForm();
const [redirect, setRedirect] = useState(false);
const onSubmit = (data) => {
const datafull = {
title: data.title,
excerpt: "nonex5",
content: data.content,
location: data.location,
company_id: "75",
category_id: data.category_id,
date_start_at: data.date_start_at,
date_end_at: data.date_end_at,
link: data.link,
};
console.log(datafull);
axios({
method: "post",
url: "url",
data: datafull,
})
.then(function (res) {
console.log("resolution", res.data);
setRedirect(true);
})
.catch(function (err) {
console.log(err);
});
};
if (redirect) return <Redirect to="/company/news" />;
// default return goes beneath
}
让我知道是否有帮助。