Reactjs 如何避免两次重定向(反应)?
我需要消除两次重定向。 从App.js转到Product.js,然后我需要重定向到/notfound。它工作,但去两次那里,甚至通过我实现开关那里。 我在哪里犯错误?我只看到了把开关放在那个里的建议,但它并没有帮助 这是我的代码: App.js:Reactjs 如何避免两次重定向(反应)?,reactjs,Reactjs,我需要消除两次重定向。 从App.js转到Product.js,然后我需要重定向到/notfound。它工作,但去两次那里,甚至通过我实现开关那里。 我在哪里犯错误?我只看到了把开关放在那个里的建议,但它并没有帮助 这是我的代码: App.js: import React from 'react'; import './App.css'; import { Route, Switch } from 'react-router-dom'; import Products from './Produ
import React from 'react';
import './App.css';
import { Route, Switch } from 'react-router-dom';
import Products from './Products';
import NotFound from './NotFound';
import Home from "./Home";
class App extends React.Component {
render() {
return (
<div>
<Switch>
<Route path="/products" component={Products} />
<Route path="/notfound" component={NotFound} />
<Route path="/" exact component={Home} />
</Switch>
</div>
);
}
}
export default App;
从“React”导入React;
导入“/App.css”;
从“react router dom”导入{Route,Switch};
从“./产品”进口产品;
从“/NotFound”导入NotFound;
从“/Home”导入主页;
类应用程序扩展了React.Component{
render(){
返回(
);
}
}
导出默认应用程序;
Product.js:
import React, { Component } from "react";
import { Redirect, Switch } from 'react-router-dom';
class Products extends Component {
state = {
toDashboard: false,
}
handleSubmit = (e) => {
e.preventDefault();
this.setState({
toDashboard: true
});
}
render() {
console.log(this.props);
if (this.state.toDashboard === true) {
return (
<div>
<Switch>
<Redirect to={{
pathname: '/notfound', state: { id: '123' }
}} />
</Switch>
</div>
);
}
return (
<div>
<h1>Products</h1>
<form onSubmit={this.handleSubmit}>
<button type="submit">Submit</button>
</form>
</div>
);
}
}
export default Products;
import React,{Component}来自“React”;
从“react router dom”导入{Redirect,Switch};
类产品扩展组件{
状态={
toDashboard:错,
}
handleSubmit=(e)=>{
e、 预防默认值();
这是我的国家({
托达什博德:没错
});
}
render(){
console.log(this.props);
if(this.state.toDashboard===true){
返回(
);
}
返回(
产品
提交
);
}
}
出口默认产品;
您可以使用历史记录。按如下方式推送
:
if (this.state.toDashboard === true) {
this.props.history.push({ pathname: '/notfound', state: { id: 123 }})
}
您可以使用
历史记录。按如下方式推送:
if (this.state.toDashboard === true) {
this.props.history.push({ pathname: '/notfound', state: { id: 123 }})
}
但我需要插入“state:{id:123}”作为道具,我不知道在你们提到的情况下如何做。请检查更新的答案。还检查了我必须重新安排它,它工作了。删除状态并将此history.push直接放在handleSubmit方法中。谢谢但我需要插入“state:{id:123}”作为道具,我不知道在你们提到的情况下如何做。请检查更新的答案。还检查了我必须重新安排它,它工作了。删除状态并将此history.push直接放在handleSubmit方法中。谢谢