【发布时间】:2023-03-19 09:22:01
【问题描述】:
我对 React 有点陌生,一直在练习使用this article 中指定的枚举渲染方法创建应用程序。
但是,我正在尝试以与本文所讨论的方式略有不同的方式应用它,更具体地说,使用它来有条件地呈现我的所有网站,除了基于lastLinkClicked 状态的<Nav />。对于 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 for home 在 WEB_PAGES 对象下。
我最初认为this 指向 WEB_PAGES 对象,但将this 更改为App 表明state 也未定义。我现在不确定该怎么做。
枚举条件渲染方法在这种规模上是否可行?如果不是,还有什么其他方法最适合这种情况?非常感谢!
【问题讨论】:
-
使用立即调用函数。
-
请检查代码并将语句从 {WEB_PAGES.link} 替换为 {WEB_PAGES[link]}
-
{WEB_PAGES[link]} 成功了,谢谢!
标签: javascript reactjs enums jsx conditional-rendering