在单击ReactJs时动态切换视图



我已经映射了来自JSON的数据列表。当我单击该项目时,它应该会打开一个爬网,其中包含来自同一 JSON 文件的其他详细信息。我能够映射我点击的所有内容,我无法切换。如何切换。

这是我的渲染方法

render() {
return (
<div>
<h1>API</h1>
<div>
{this.state.apis.map(api => (
<div
key={api.id}
id={api.id}
onClick={this.handleCrawl}>
{api.title}

</div>
))}
</div>
<div>
{this.state.apis.map(api => (
<div
key={api.id}
id={api.id}>
{this.state.showCrawl[api.id] && (
<SwaggerUI url={api.opening_crawl}/>
)}
</div>
))}
</div>
</div>
);
}

这是切换方法。当我单击一个项目时,将显示 SwaggerUI 组件,如果我单击相同的链接,它就会隐藏。

问题是如果我单击第二个链接,第一个链接仍然显示。我需要关闭其他视图。

handleCrawl = e => {
const { id } = e.target;
this.setState(current => ({
showCrawl: { ...current.showCrawl, [id]: !current.showCrawl[id] }
}));
};

只是不要传播前一个状态的道具。

试试这个:

handleCrawl = e => {
const { id } = e.target;
this.setState(current => ({
showCrawl: { [id]: !current.showCrawl[id] }
}));
};

因为在您的代码中:

初始状态:

{showCrawl: {}}

假设您第一次单击第一个(id: 1(,您的状态变为:

{showCrawl: {1: true}}

然后你点击第二个(ID: 2(

{showCrawl: {1: true, 2: true}}

这不是你的预期。右?

所以不要分散财产,它应该进展顺利。

通常,您可以在 react 组件中显示或隐藏元素,如下所示:

{this.state.showComponent ? (<Component/>) : (null)}

作为替代方案,您可以使用showprop 控制元素在组件本身中的隐藏/显示:

<Component show={this.state.showComponent} />

--编辑

我想我误解了你的问题。您的问题是,您一次只希望SwaggerUI显示一件事,但它显示的是多件事。

这是因为您设计函数的方式,

handleCrawl = e => {
const { id } = e.target;
this.setState(current => ({
showCrawl: { ...current.showCrawl, [id]: !current.showCrawl[id] }
}));
};

您只会将 ID 添加到 showCrawl,而不会更改您之前切换的 ID。你必须修复这个功能

最新更新