我基本上正在重构我的 React 组件以支持新的无状态功能组件 React functional component 。但是,我对功能组件中的 if-else
语法感到困惑。
旧代码(工作正常):它的作用基本上是查找用户当前是否已登录。如果是,则重定向到主页,否则重定向到登陆页面。 CurrentUser 组件返回一个 prop currentUser
并检查当前状态
import React, {Component} from "react";
import currentUser from "shared/components/CurrentUser";
import Home from "../Home";
import Landing from "../Landing";
class DefaultRouteHandler extends Component {
render() {
if (!this.props.currentUser) {
return (<Landing />);
} else {
return (<Home />);
}
}
}
export default currentUser(DefaultRouteHandler);
新代码:现在,如果 currentUser 的状态为 false,我应该如何检查 else
条件。正如您现在所看到的,它将始终返回主页。
import React from "react";
import currentUser from "shared/components/CurrentUser";
import Home from "../Home";
import Landing from "../Landing";
const DefaultRouteHandler = ({currentUser}) => (
<Home />
);
export default DefaultRouteHandler;
最后在我的route.jsx中我调用上述组件
<IndexRoute component={DefaultRouteHandler} />
如果您需要更多信息,请告诉我。我还可以粘贴我的 CurrentUser
组件代码。但是,我认为这对这个问题没有任何作用。
最佳答案
const DefaultRouteHandler = ({currentUser}) => {
if (currentUser) {
return <Home />;
}
return <Landing />;
};
关于javascript - React 无状态函数组件中的 if-else,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34045348/