内容未在条件语句中呈现

问题描述 投票:0回答:2

所以目前我有一个反应组件。我已经声明了一个数组,其中包含一些对象的一些示例数据。由于'currentStep'的初始状态为0,我期望<div>Screen 1</div>呈现,但是,我得到的只是一个空白屏幕。

有任何想法吗?

import React, { Component } from 'react';

/**
 * sample data to pass through
 */

const contents =
  [
    { title: 'First Screen', step: 0, children: <div>Screen 1</div> },
    { title: 'Second Screen', step: 1, children: <div>Screen 2</div> },
    { title: 'Third Screen', step: 2, children: <div>Screen 3</div> },
  ];

class Wizard extends Component {
  state = {
    currentStep: 0,
  }

  Content = () => {
    const { currentStep } = this.state;
    contents.map((content) => {
      if (content.step === currentStep) { return content.children; }
      return null;
    });
  }

  render() {
    return (
      <div>{this.Content()}</div>     
    );
  }
}

export default Wizard;
javascript reactjs
2个回答
2
投票

您需要在内容中返回地图。现在你什么也没有回来。例如:

Content = () => {
  const { currentStep } = this.state;
  return contents.map((content) => {
    if (content.step === currentStep) { return content.children; }
    return null;
  });
}

2
投票

你的Content函数实际上并没有返回任何东西,但是你的map函数是。如果你return contents.map(...),那么你应该得到你期望的。

© www.soinside.com 2019 - 2024. All rights reserved.