gpt4 book ai didi

javascript - 不要嵌套三元表达式 - 替代

转载 作者:行者123 更新时间:2023-11-30 14:10:24 25 4
gpt4 key购买 nike

我有一个可以有 4 种状态的 React 组件:advisoryResults、results、noResults、newAccount。

我认为用三元表达式来做是有意义的,但这是不允许的,有什么好的替代方法?

export default class Home extends React.Component {
state = {
isAdmin: false
};

render() {
const { isAdmin } = this.state;
return (
<div>
<Header />
<div css={innerWrap}>
{isAdmin ? (
<Button
onClick={this.handleAddNewContact }
>
Add new Contact
</Button>
) : (
''
)}
{searchMode === searchModes.advisoryPanels ? (
<>
<SearchAdvisoryPanels />
<div css={{ textAlign: 'center', margin: '60px auto' }}>
<ManAtDesk />
</div>
</>
) : searchMode === searchModes.noResultsPanel ? (
<SearchNoResultsPanel />
) : searchMode === searchModes.resultsPanel ? (
accountInfo.map((info, index) => (
<SearchResultPanel info={info} isAdmin={isAdmin} key={index} />
))
) : searchMode === searchModes.addContactPanel ? (
<AddNewContactForm
onCancelAccount={this.onCancelAccount}
onSaveAccount={this.onSaveAccount}
/>
) : null}
</div>
</div>
);
}
}

请指教。

最佳答案

我建议这样做:

export default class Home extends React.Component {
state = {
isAdmin: false
};

onCancelAccount = () => {};
onSaveAcciont = () => {};

renderSearchResults = (searchMode) => {
const { info, isAdmin, index } = this.props;

switch (searchMode) {
case searchModes.advisoryPanels:
return this.renderAdvisoryPanels();
case searchModes.noResultsPanel:
return <SearchNoResultsPanel />;
case searchModes.resultsPanel:
return <SearchResultPanel info={info} isAdmin={isAdmin} key={index} />;
case searchModes.addContactPanel:
return (
<AddNewContactForm
onCancelAccount={this.onCancelAccount}
onSaveAccount={this.onSaveAccount}
/>
);
default:
return null;
}
}

renderAdvisoryPanels = () => (
<React.Fragment>
<SearchAdvisoryPanels />
<div css={{ textAlign: 'center', margin: '60px auto' }}>
<ManAtDesk />
</div>
</React.Fragment>
);

render() {
const { isAdmin } = this.state;

return (
<div>
<Header />
<div css={innerWrap}>
{isAdmin && (
<Button onClick={this.handleAddNewContact}>Add new Contact</Button>
)}
{this.renderSearchResults(searchMode)}
</div>
</div>
);
}
}

有些处理程序/ Prop 在您的示例中不是立即可见的,所以如果我出错了请修复。

关于javascript - 不要嵌套三元表达式 - 替代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54569609/

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