我创建了一个名为EnsureLoggedInContainer
的组件,它包装了只有登录用户才能访问的组件:
ReactDOM.render(
<Provider store={store}>
<BrowserRouter>
<div>
<Switch>
<Route path="/login" render={(props) => {
if (isAuthenticated()) {
return <Redirect to='/' />;
} else {
return <LoginForm {...props}/>
}
}
} />
<EnsureLoggedInContainer>
<Route exact path="/api/group" component={GroupList}/>
<Route component={Home}/>
</EnsureLoggedInContainer>
</Switch>
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container'));
class EnsureLoggedInContainer extends Component {
componentDidMount() {
if (!isAuthenticated()) {
const redirected_from = this.props.location.state ? this.props.location.state.from.pathname : '/';
this.props.history.push(redirected_from);
dispatch(setRedirectUrl(currentURL))
this.props.history.replace("/login")
}
}
render() {
if (isAuthenticated()) {
return(
<div>
<AppNavBar />
<ComponentsNavBar />
{this.props.children}
</div>
);
} else {
return <noscript />;
}
}
}
export default EnsureLoggedInContainer;
现在,Home
组件始终呈现。如何使其成为不匹配路线,例如只有当路径与任何提供的路径路径不匹配时才会呈现?
我将path="*"
添加到<Route component={Home}/>
,但它仍然会呈现。
答案 0 :(得分:0)
如果您使用 public ActionResult Subcategory(string item)
{
//Logic calling Api content goes here
var SearchresponseData = responseMessage.Content.ReadAsStringAsync().Result;
JavaScriptSerializer JssSearch = new JavaScriptSerializer();
List<Result> Jsonresult = (List<Result>)JssSearch.Deserialize(SearchresponseData, typeof(List<Result>));
var Model= new ModelName();
{
Model.AllAds = new List<Result>();
Model.AllAds = Jsonresult;
}
return PartialView("_Details", Model);
}
,请尝试:
react-router 4
(不含<Route component={YourNotFoundPage}/>
)
请注意,您的问题可能会重复,您也应该see this。
希望有所帮助。
答案 1 :(得分:0)
似乎整个设计都是错误的。我跟着Private Route pattern并解决了问题:
limitTo
然后像这样使用PrivateRoute:
export const PrivateRoute = ({component: Component, componentProps, ...rest }) => {
return (<Route {...rest} render={(props) => {
if (isAuthenticated()) {
return (
<div>
<AppNavBar />
<ComponentsNavBar />
<Component {...props} {...componentProps}/>
</div>
)
} else {
return <Redirect to={{ pathname: '/login', state: { from: props.location } }} />;
}
}
} />);
}
export default PrivateRoute;