如何在使用Hooks的react router v5中发出POST请求后重定向



===p.S.我找到了一个解决方案并写了评论。

我想制作一个表单,并在重定向后在另一个域中显示其服务器响应。请求从/发送,服务器处理该请求,然后浏览器在/result域中看到服务器的响应。

按照惯例,这很简单。这写为

====index.html====

<form action="/result" method="POST">
<input type="text" placeholder="Your Name" />
<input type="submit" />
</form>

还有更多的例子,如:https://www.w3schools.com/html/tryit.asp?filename=tryhtml_form_post

我想写如上所述的React代码,然而,我在浏览器历史记录和使用params重定向方面遇到了困难。我的反应如下。它不会将浏览器发送的响应传递到/result域。

====App.js====

function App() {
return (
<BrowserRouter>
<div>
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/result">
<Result />
</Route>
</Switch>
</div>
</BrowserRouter>
);
}
function Home() {
const [submitted, setSubmitted] = useState(false);
const [content, setContent] = useState("");
const history = useHistory();
const handleSubmit = (event) => {
event.preventDefault()
fetch('https://api.example.com')
.then(response => response.json())
setSubmitted(true);
history.push("/"); // because Redirect override history, this line enables browser back button (I guess there should be a smarter way)
}
if (submitted) {
return <Redirect to='/result' /> // I want to pass fetched API response to /result
}
return (
<div>
<h1>Send content to server</h1>
<form onSubmit={handleSubmit}>
<label>
Content:
<input name="content" type="text" {...bindContent} />
</label>
<input type="submit" value="Submit" />
</form>
</div>
);
}
function Result(response) {
return <h2>Browser received {response}</h2>
}

从上面的评论中,您似乎找到了问题的解决方案,但对于任何有相同问题的人来说,您想做的是通过useHistory钩子作为const history = useHistory();,然后通过history.push("/result", { params: data });发送提交时的数据(第二个参数是包含对象params的状态(,在要访问params的组件中,您将使用useLocation钩子作为const location = useLocation();然后是location.state.params,所以在主组件中,你可以进行

主页.js

const handleSubmit = event => {
event.preventDefault();
fetch("https://jsonplaceholder.typicode.com/users")
.then(response => {
return response.json();
})
.then(data => {
history.push("/result", { params: data });
});
};
// Rest of the Code

并且在您想要在中使用的组件中

Result.js

import React from "react";
import { useLocation } from "react-router-dom";
export default function Result() {
const location = useLocation();
const data = location.state.params;
console.log(data);
return <h2>Browser received </h2>;
}

Codesandbox的工作示例

最新更新