[英]Why is my Redirect react-router not working?
我正在尝试创建一个 function 用户将在其中创建用户名和密码,并在点击提交按钮后,他们将被重定向到登录页面。 为此,我使用了重定向 react-router。
唯一的问题是,当我单击提交按钮时,它不会将我重定向到另一个页面。 我什至尝试过“/Link”,但也没有用。 我究竟做错了什么?
我的 App.js
class App extends Component {
render() {
return (
<Router>
<div className="App">
<Route exact path = '/' component={Account}/>
<Route path="/SignIn" component={SignIn}/>
</div>
</Router>
)
}
}
和我的帐户组件
if (username.length < 1) {
return document.getElementById('error').innerHTML = ("Please enter a Password or Username");
}
if (password.length < 1) {
return document.getElementById('error').innerHTML = ("Please enter a Password or Username");
}
apiClient.signUp(username, password) .then((response) => {
console.log(response)
if (response === 'Account Created') {
<Redirect to = "/SignIn"/>
}
})
.catch(error => {
console.log('Error found when creating meeting');
})
}
你不能在回调中像这样返回 JSX。
if (username.length < 1) {
return document.getElementById('error').innerHTML = ("Please enter a Password or Username");
}
if (password.length < 1) {
return document.getElementById('error').innerHTML = ("Please enter a Password or Username");
}
apiClient.signUp(username, password) .then((response) => {
console.log(response)
if (response === 'Account Created') {
<Redirect to="/SignIn"/> // <-- this isn't rendered into the DOM!
}
})
.catch(error => {
console.log('Error found when creating meeting');
})
}
Redirect
不会呈现到 DOM 中以产生任何效果。
使用history
object 强制发出重定向到登录页面。
由于Account
直接由接收路由 props的Route
组件渲染,因此history
将作为 props 传递。 路由推送是history.push
,重定向是history.replace
。 使用replace
回调重定向到新路由。
if (username.length < 1) {
return document.getElementById('error').innerHTML = ("Please enter a Password or Username");
}
if (password.length < 1) {
return document.getElementById('error').innerHTML = ("Please enter a Password or Username");
}
apiClient.signUp(username, password) .then((response) => {
console.log(response)
if (response === 'Account Created') {
props.history.replace("/SignIn"); // <-- imperatively redirect
}
})
.catch(error => {
console.log('Error found when creating meeting');
})
}
如果您仍然喜欢使用Redirect
组件,则需要从Account
组件返回和呈现它。 保留并设置一些 state 组件是否应有条件地呈现Redirect
。
const [doRedirect, setDoRedirect] = useState(false);
在上述回调中,如果满足重定向条件,则更新 state。
if (username.length < 1) {
return document.getElementById('error').innerHTML = ("Please enter a Password or Username");
}
if (password.length < 1) {
return document.getElementById('error').innerHTML = ("Please enter a Password or Username");
}
apiClient.signUp(username, password) .then((response) => {
console.log(response)
if (response === 'Account Created') {
setDoRedirect(true); // <-- set do redirect
}
})
.catch(error => {
console.log('Error found when creating meeting');
})
}
然后在组件 return 有条件地渲染Redirect
组件。
if (doRedirect) return <Redirect to="/SignIn"/>;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.