[英]How can I redirect a /:user link to 404 page in react redux
I am trying to use /:user and if using the match.params.user method to get data from redux and then returning data from redux but when I add a Route which is unknown I get a lot of errors how can I redirect my website to a 404 page when the router path is not matched.我正在尝试使用 /:user 并且如果使用 match.params.user 方法从 redux 获取数据,然后从 redux 返回数据但是当我添加一个未知的路由时,我收到很多错误我如何重定向我的网站当路由器路径不匹配时跳转到 404 页面。
import React from 'react';
import Main from "./Main"
import Navb from "./Navbar";
import Notfound from './Notfound';
import { BrowserRouter , Route , Switch , Redirect } from "react-router-dom"
class App extends React.Component {
render() {
return (
<BrowserRouter >
<Navb />
<Switch>
<Route path = "/:user" exact component = {Main} />
<Route path="/404" component={Notfound} />
<Redirect from="*" to="/404" />
</Switch>
</BrowserRouter>
)
}
}
export default App;
-----------------------------
import { connect } from "react-redux";
import {Link} from "react-router-dom"
function Main(props) {
function hello(){
let id = props.prop.id;
props.data(id);
}
return (
<div className = "row">
<div className="col text-center mt-5 w-25 ms-5" key = {props.prop.id}>
<Link to={props.prop.path} className="text-danger lead">{props.prop.Name}</Link>
<p className="lead text-success mt-5">
{props.prop.text}
</p>
<button className="btn btn-outline-danger" onClick={hello}>
Delete
</button>
</div>
</div>
);
}
const mapStateToProps = (state , ownparams) =>{
let user = ownparams.match.params.user;
return{
prop : state.sta.data.find(card => card.Name === user )
}
}
const mapDispatchToProps = (dispatch) =>{
return{
data :(id) => dispatch({ type : "hello" ,id })
}
}
export default connect(mapStateToProps , mapDispatchToProps)(Main);
--------------------------
const sta = {
data : [
{Name : "Card1" ,path : "/Card1", id : 1 , text : " Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis,"},
{Name : "Card2" ,path : "/Card2", id :2 , text : " The European languages are members of the same family. Their separate existence is a myth. For science, music, sport, etc, Europe uses the same vocabulary. The languages only differ in"},
{Name : "Card3" ,path : "/Card3", id :3 , text : "The quick, brown fox jumps over a lazy dog. DJs flock by when MTV ax quiz prog. Junk MTV quiz graced by fox whelps. Bawds jog, flick quartz, vex nymphs. Waltz, bad nymph, for quick jigs vex! Fox nymphs grab quick-jived waltz. Brick quiz whangs jumpy veldt fox. Bright vixens"},
]
}
function rootReducer(state = {sta} , action) {
try {
console.log(action);
return state;
} catch (error) {
console.log(error.message);
}
}
export default rootReducer;
尝试这个:
<Route path="*" exact={true} component={NotFound} />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.