gpt4 book ai didi

javascript - 使用条件时不显示 React 组件

转载 作者:行者123 更新时间:2023-12-03 05:53:31 26 4
gpt4 key购买 nike

我正在关注 CodeSchool 的 React JS 示例。我已经能够遵循这些例子了。问题是当我尝试实现 IF 条件以将不同的数据传递给组件时。未显示的组件是“注释”。查看 _getComments 函数的内部。如果我使用 If 条件,请参阅 fiddle :https://jsfiddle.net/joelgb/vxtkpzog/15/ ,来决定将传递哪个数组,该代码将不起作用。但是,如果我只是将下面的代码放在没有任何 If 的情况下,组件注释就会正确呈现。

const commentsList = [
{id: 1, author: "author1", body: "body1"},
{id: 2, author: "author2", body: "body2"},
{id: 3, author: "author3", body: "body3"}
];

请注意,使用这种方法是行不通的。

var commentsList;
if (a=='a'){
commentsList = [
{id: 1, author: "author1", body: "body1"},
{id: 2, author: "author2", body: "body2"},
{id: 3, author: "author3", body: "body3"}
];
}
else
{
commentsList = [
{id: 1, author: "author4", body: "body4"},
{id: 2, author: "author5", body: "body5"},
{id: 3, author: "author6", body: "body6"}
];
}

有人可以指出我的错误吗?

最佳答案

你几乎做对了,你忘了调用comments()

这个

class CommentBox extends React.Component{
render() {
const comments = this._getComments.bind(this,'a');
return (
<div>
<h3>Comments</h3>
{comments} // <--- You are not calling comments
<button onClick={this._getComments.bind(this,'b')}>north</button>
</div>
);
}
...
}

应该是

class CommentBox extends React.Component{
render() {
const comments = this._getComments.bind(this,'a');
return (
<div>
<h3>Comments</h3>
{comments()}
<button onClick={this._getComments.bind(this,'b')}>north</button>
</div>
);
}
...
}

your jsfiddle

A better solution using state

关于javascript - 使用条件时不显示 React 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40045034/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com