我对 React 有点陌生,并且一直在通过使用本文中指定的枚举渲染方法创建应用程序来练习。
但是,我试图以与文章所讨论的方式略有不同的方式应用它,更具体地说,使用它来有条件地渲染我的所有网站,除了<Nav />
基于lastLinkClicked
状态的网站。对于 WEB_PAGES 对象中列出的每个条件,我都有不同的页面类。
也许我误解了这种方法,因为我对枚举没有太多经验,但我的页面没有正确呈现。这是我的代码:
class App extends Component {
constructor(props){
super(props);
this.state = {
x: ...
y: ...
z: ...
lastClickedLink: 'home' //changes to 'new', 'settings', etc. using another function not listed here
}
}
render() {
function onLinkClick(link) {
const WEB_PAGES = {
home: <Home
x={this.state.x}
/>,
new: <NewPost />,
settings: <Settings />,
signup: <SignUp />,
login: <Login />
};
return (
<div>
{WEB_PAGES.link}
</div>
);
}
return (
<div>
<Nav
y={this.state.y}
z={this.state.z}
/>
{onLinkClick(this.state.lastClickedLink)}
</div>
);
}
}
export default App;
为了简洁起见,我删除了一些代码。我在此设置中遇到的错误是TypeError: Cannot read property 'state' of undefined
针对 WEB_PAGES 对象下的主页。
我最初认为它this
指向 WEB_PAGES 对象,但更改this
为App
显示它state
也是未定义的。我现在不确定该怎么做。
枚举条件渲染方法在这种规模上是否可行?如果不是,还有什么其他方法最适合这种情况?非常感谢!