我对 React 有点陌生,一直在练习使用 this article 中指定的枚举渲染方法创建应用程序.
但是,我尝试以与文章中提到的略有不同的方式应用它,更具体地说,使用它来有条件地呈现我网站的所有内容,<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
也未定义。我不太确定此时该做什么。
枚举条件渲染方法在这种规模上是否可行?如果不是,还有什么其他方法最适合这种情况?非常感谢!
最佳答案
在 javascript 中,当您使用 function
关键字创建函数时,它会创建自己的新作用域并创建默认对象 this
。因此,当您尝试访问 this.state.x
时,它不会在函数内声明属性。它变成了 this.undefined.x
。所以它给出了错误。
而箭头函数 {(() => {})}
不创建此对象,而是创建内部范围。
尝试在您的代码中使用以下渲染方法:
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>
);
}
关于javascript - ReactJS:使用枚举进行条件渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50245505/