Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

javascript - 使用React,在以下情况下如何编写更友好,更清晰的条件渲染(With React, how to write friendlier and clearer conditional rendering given the following [closed])

In my React 16 app, I have the following render function:(在我的React 16应用中,我具有以下渲染功能:)

render() { const { isLoading, leverJobData, isApiError } = this.state; return ( <Openings.Container> <Openings.StyledH4>Open roles:</Openings.StyledH4> {isLoading && <h4>Loading...</h4>} {!isLoading && isApiError && <h4>Something went wrong. Please try again later!</h4>} {!isLoading && !isApiError && leverJobData.length === 0 && ( <h4>There are no openings at this time.</h4> )} {!isLoading && !isApiError && leverJobData.length > 0 && ( <>{this.renderJobOpenings(leverJobData)}</> )} </Openings.Container> ); } Is there a cleaner way to write the above or is this the right way to do conditional rendering in React?(有没有一种更干净的方式编写以上内容,或者这是在React中进行条件渲染的正确方法?)   ask by AnApprentice translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When I have blocks like this, I like to break out the conditions and describe exactly what they're doing.(当我有这样的障碍时,我喜欢打破条件并准确描述他们在做什么。)

For example:(例如:) render() { const { isLoading, leverJobData, isApiError } = this.state; const hasError = !isLoading && isApiError; const noJobsAvailable = !isLoading && !isApiError && leverJobData.length === 0; const hasJobsAvailable = !isLoading && !isApiError && leverJobData.length > 0; return ( <Openings.Container> <Openings.StyledH4>Open roles:</Openings.StyledH4> {isLoading && <h4>Loading...</h4>} {hasError && <h4>Something went wrong. Please try again later!</h4>} {noJobsAvailable && <h4>There are no openings at this time.</h4>} {hasJobsAvailable && this.renderJobOpenings(leverJobData)} </Openings.Container> ); }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...