gpt4 book ai didi

reactjs - React-router-dom 链接不起作用

转载 作者:行者123 更新时间:2023-12-03 13:26:06 24 4
gpt4 key购买 nike

我从react-router迁移到react-router-dom并修复了所有错误。但是,现在单击链接时,网址正在更改,但相应的 View 未呈现。

这是我的应用程序的结构:

index.js

ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<HashRouter>
<App>
<Switch>
<Route path="signin" component={Signin} />
<Route path="about" component={About} />
<Route path="signout" component={Signout} />
<Route path="signup" component={Signup} />
<Route path="thanks" component={Thanks} />
<Route path="tasks" component={ requireAuth(Task) }/>
<Route path="/" component={ Content }/>

</Switch>
</App>
</HashRouter>
</Provider>
, document.querySelector('.container'));

app.js

class App extends Component {
render() {
return (
<div>
<Header/>
{this.props.children}
<Footer/>
</div>
);
}
}

export default withRouter(App);

header.js

class Header extends Component {

showLoginButton() {
if (this.props.authenticated) {
// show a link to sign out
return [<span className="loginBtn">
<Link to="/signout">Sign Out</Link>
</span>,
<span className="loginBtn">
<Link to="/tasks">Tasks</Link>
</span>
]
} else {
// show a link to sign in or sign up
return [
<span className="loginBtn" key={1}>
<Link className="nav-link" to="/signin">Sign In</Link>
</span>,
<span className="loginBtn" key={2}>
<Link className="nav-link" to="/signup">Sign Up</Link>
</span>,
<span className="loginBtn" key={3}>
<Link className="nav-link" to="/about">About</Link>
</span>
];
}
}

render() {
return (
<div className="header">
<span className="logo">
<Link to="/" className="navbar-brand">company</Link>
</span>
{this.showLoginButton()}
</div>
);
}
}

function mapStateToProps(state) {
return {
authenticated: state.auth.authenticated
};
}

export default withRouter(connect(mapStateToProps)(Header));

我尝试使用路由器,如帖子 https://stackoverflow.com/a/43811162/888181 中提到的那样,但仍然不起作用!

最佳答案

尝试将根路径移动到顶部,并确保将exact放在路径前面。另外,您应该为其他路径添加 /

<Switch>
<Route exact path="/" component={ Content }/>
<Route path="/signin" component={Signin} />
<Route path="/about" component={About} />
<Route path="/signout" component={Signout} />
<Route path="/signup" component={Signup} />
<Route path="/thanks" component={Thanks} />
<Route path="/tasks" component={ requireAuth(Task) }/>
</Switch>

引用:https://reacttraining.com/react-router/web/api/Switch

关于reactjs - React-router-dom 链接不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44476918/

24 4 0
文章推荐: reactjs - react 主入口点
文章推荐: reactjs - 无法设置属性 createElement of#,它只是一个 getter