我对React有点新意,并且一直在使用this article中指定的枚举渲染方法创建应用程序。
但是,我试图以与文章所述略有不同的方式应用它,更具体地说,使用它来有条件地呈现我的所有网站,除了基于<Nav />
的{{1}}州。我为WEB_PAGES对象中列出的每个条件都有不同的页面类。
也许我误解了这种方法,因为我对枚举没有太多经验,但我的页面渲染不正确。这是我的代码:
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
更改为this
表明App
也未定义。我现在还不确定该怎么做。
enums条件渲染方法在这个规模上是否可行?如果没有,那么对于这种情况,哪种其他方法最理想?非常感谢!
答案 0 :(得分:1)
在javascript中,当您使用function
关键字创建函数时,它会创建自己的新范围,并创建默认对象this
。因此,当您尝试访问this.state.x
时,它将不会在函数内声明属性。它变为this.undefined.x
。所以它给出了错误。
而箭头函数{(() => {})}
不会创建此对象,而是创建内部范围。
尝试在代码中使用render方法:
render() {
return (
<div>
<Nav
y={this.state.y}
z={this.state.z}
/>
{((link) => {
const WEB_PAGES = {
home: <Home
x={this.state.x}
/>,
new: <NewPost />,
settings: <Settings />,
signup: <SignUp />,
login: <Login />
};
return (
<div>
{WEB_PAGES[link]}
</div>
);
})(this.state.lastClickedLink)}
</div>
);
}
答案 1 :(得分:0)
当您尝试使用{WEB_PAGES[link]}
时使用.
它将无效