--- id: 5a24c314108439a4d4036185 title: Use && for a More Concise Conditional challengeType: 6 isRequired: false videoUrl: '' localeTitle: 使用&&获得更简洁的条件 --- ## Description
if / else语句在最后一次挑战中起作用,但是有一种更简洁的方法来实现相同的结果。想象一下,您正在跟踪组件中的多个条件,并且您希望根据这些条件中的每个条件呈现不同的元素。如果你写了很多else if语句来返回略有不同的UI,你可能会重复代码,这会留下错误的余地。相反,您可以使用&& logical运算符以更简洁的方式执行条件逻辑。这是可能的,因为您要检查条件是否为true ,如果是,则返回一些标记。下面是一个示例: {condition && <p>markup</p>}如果conditiontrue ,则返回标记。如果条件为false ,则在评估condition后操作将立即返回false并且不返回任何内容。您可以直接在JSX中包含这些语句,并在每个语句之后写入&&多个条件串在一起。这允许您在render()方法中处理更复杂的条件逻辑,而无需重复大量代码。
## Instructions
再次解决前面的示例,因此h1仅在displaytrue呈现,但使用&& logical运算符而不是if/else语句。
## Tests
```yml tests: - text: MyComponent应该存在并呈现。 testString: 'assert((function() { const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); return mockedComponent.find("MyComponent").length; })(), "MyComponent should exist and render.");' - text: 当display设置为true ,应该渲染divbuttonh1 。 testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: true}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(updated.find("div").length === 1 && updated.find("div").children().length === 2 && updated.find("button").length === 1 && updated.find("h1").length === 1, "When display is set to true, a div, button, and h1 should render."); }; ' - text: 当display设置为false ,只应呈现divbutton 。 testString: 'async () => { const waitForIt = (fn) => new Promise((resolve, reject) => setTimeout(() => resolve(fn()), 250)); const mockedComponent = Enzyme.mount(React.createElement(MyComponent)); const state_1 = () => { mockedComponent.setState({display: false}); return waitForIt(() => mockedComponent )}; const updated = await state_1(); assert(updated.find("div").length === 1 && updated.find("div").children().length === 1 && updated.find("button").length === 1 && updated.find("h1").length === 0, "When display is set to false, only a div and button should render."); }; ' - text: render方法应该使用&& logical运算符来检查this.state.display的条件。 testString: 'getUserInput => assert(getUserInput("index").includes("&&"), "The render method should use the && logical operator to check the condition of this.state.display.");' ```
## Challenge Seed
```jsx class MyComponent extends React.Component { constructor(props) { super(props); this.state = { display: true } this.toggleDisplay = this.toggleDisplay.bind(this); } toggleDisplay() { this.setState({ display: !this.state.display }); } render() { // change code below this line return (

Displayed!

); } }; ```
### After Test
```js console.info('after the test'); ```
## Solution
```js // solution required ```