Как я могу отфильтровать данные JSON из вызова API в реагировать на различные разделы компонента - PullRequest
1 голос
/ 23 октября 2019

У меня есть 2 объекта json, которые содержат информацию о периоде продаж, основанную на данных месяца и года. Эти данные включают проданные единицы, валовой доход, год к дате, ИТОГО, месяц к дате, ЕЖЕДНЕВНЫЕ СРЕДСТВА, расходы, чистые доходы и PER UNIT. Я не хочу отобразить это путем создания цикла. Я хочу извлечь нужные столбцы и поместить их в разные сегменты В коде React Semantic UI Ниже большая часть причин, по которым я не хочу отображать их и выполнять цикл, заключается в том, что я такжехочу повторно использовать данные в старшей диаграмме, чтобы сделать несколько круговых диаграмм. Так что Я смогу повторно использовать Данные после фильтрации. Я буду помещать значения в Заголовки и <Statistic.Value>{this.state.data.filter(item => item.match "item.gross"}</Statistic.Value> или что-то в этом роде

Вот моя выборка

class FetchTest extends Component {
    state = {
      data: [],
      loading: true,
      error: false
    }
    componentDidMount() {
      // Pick whatever host/port your server is listening on
      fetch('/product/1')
        .then(res => { // <-- The `results` response object from your backend
          // fetch handles errors a little unusually
          if (!res.ok) {
            throw res;
          }
          // Convert serialized response into json
          return res.json()
        }).then(data => {
          // setState triggers re-render
          this.setState({loading: false, data});
        }).catch(err => {
          // Handle any errors
          console.error(err);
          this.setState({loading: false, error: true});
        });
    }

Вот сегменты, в которые я хочу поместить эту информацию

<div>
  <Header as="h2" textAlign="left" className="ui header">
    Sales
  </Header>
  <Segment.Group horizontal>
    <Segment className="violet horizontal">
      <Header as="h3" textAlign="left" className="ui header">
        <Icon className="violet icon" name="dolly" />
        Units Sold
      </Header>
      <Grid className="ui two column grid">
        <Grid.Row>
          <Grid.Column>
            <Header as="h4" textAlign="left">
              YTD<Header sub>Year to Date</Header>
            </Header>
            <Statistic horizontal className="mini" floated="left">
              <Statistic.Value>91.9K</Statistic.Value>{" "}
              {/* This is where  dashboards.sales.period.YTD.sold | shortNum was */}
              <Statistic.Label>Total</Statistic.Label>
            </Statistic>
            <Statistic horizontal className="mini lnegdot2em" floated="left">
              <Statistic.Value>321.8</Statistic.Value>
              {/* This is where  dashboards.sales.period.YTD.avgSold | shortNum */}
              <Statistic.Label>Daily Avg</Statistic.Label>
            </Statistic>
          </Grid.Column>
          <Grid.Column>
            <Header as="h4" textAlign="left">
              MTD<Header sub>Month to Date</Header>
            </Header>
            <Statistic horizontal className="ui mini" floated="left">
              <Statistic.Value>49.2K</Statistic.Value>
              <Statistic.Label>Total</Statistic.Label>
            </Statistic>
            <Statistic horizontal className="mini lnegdot2em" floated="left">
              <Statistic.Value>3.5K</Statistic.Value>
              <Statistic.Label>Daily Avg</Statistic.Label>
            </Statistic>
          </Grid.Column>
        </Grid.Row>
      </Grid>
    </Segment>
    <Segment color="olive">
      <Header as="h3" textAlign="left">
        <Icon color="olive" className="alternative outline" name="money" />
        Gross Revenue
      </Header>
      <Grid className="ui two column grid">
        <Grid.Row>
          <Grid.Column>
            <Header as="h4" textAlign="left">
              YTD<Header sub>Year to Date</Header>
            </Header>
            <Statistic horizontal className="mini" floated="left">
              <Statistic.Value>91.9K</Statistic.Value>
              <Statistic.Label>Total</Statistic.Label>
            </Statistic>
            <Statistic horizontal className="mini lnegdot2em" floated="left">
              <Statistic.Value>321.8</Statistic.Value>
              <Statistic.Label>Daily Avg</Statistic.Label>
            </Statistic>
            <Statistic
              horizontal
              className="mini lnegdot2em unitmg"
              floated="left"
            >
              <Statistic.Value>321.8</Statistic.Value>
              <Statistic.Label>PER UNIT</Statistic.Label>
            </Statistic>
          </Grid.Column>
          <Grid.Column>
            <Header as="h4" textAlign="left">
              MTD<Header sub>Month to Date</Header>
            </Header>
            <Statistic horizontal className="ui mini" floated="left">
              <Statistic.Value>49.2K</Statistic.Value>
              <Statistic.Label>Total</Statistic.Label>
            </Statistic>
            <Statistic horizontal className="mini lnegdot2em" floated="left">
              <Statistic.Value>3.5K</Statistic.Value>
              <Statistic.Label>Daily Avg</Statistic.Label>
            </Statistic>
            <Statistic
              horizontal
              className="mini lnegdot2em unitmg"
              floated="left"
            >
              <Statistic.Value>321.8</Statistic.Value>
              <Statistic.Label>PER UNIT</Statistic.Label>
            </Statistic>
          </Grid.Column>
        </Grid.Row>
      </Grid>
    </Segment>
    <Segment color="red">
      <Header as="h3" textAlign="left">
        <Icon color="red" name="cogs" />
        Expenses
      </Header>
      <Grid className="ui two column grid">
        <Grid.Row>
          <Grid.Column>
            <Header as="h4" textAlign="left">
              YTD<Header sub>Year to Date</Header>
            </Header>
            <Statistic horizontal className="mini" floated="left">
              <Statistic.Value>91.9K</Statistic.Value>
              <Statistic.Label>Total</Statistic.Label>
            </Statistic>

            <Statistic horizontal className="mini lnegdot2em" floated="left">
              <Statistic.Value>321.8</Statistic.Value>
              <Statistic.Label>Daily Avg</Statistic.Label>
            </Statistic>
            <Statistic
              horizontal
              className="mini lnegdot2em unitmg"
              floated="left"
            >
              <Statistic.Value>321.8</Statistic.Value>
              <Statistic.Label>PER UNIT</Statistic.Label>
            </Statistic>
          </Grid.Column>
          <Grid.Column>
            <Header as="h4" textAlign="left">
              MTD<Header sub>Month to Date</Header>
            </Header>
            <Statistic horizontal className="ui mini" floated="left">
              <Statistic.Value>49.2K</Statistic.Value>
              <Statistic.Label>Total</Statistic.Label>
            </Statistic>
            <Statistic horizontal className="mini lnegdot2em" floated="left">
              <Statistic.Value>3.5K</Statistic.Value>
              <Statistic.Label>Daily Avg</Statistic.Label>
            </Statistic>
            <Statistic
              horizontal
              className="mini lnegdot2em unitmg"
              floated="left"
            >
              <Statistic.Value>321.8</Statistic.Value>
              <Statistic.Label>PER UNIT</Statistic.Label>
            </Statistic>
          </Grid.Column>
        </Grid.Row>
      </Grid>
    </Segment>
    <Segment color="green">
      <Header as="h3" textAlign="left">
        <Icon color="green" name="dollar sign" />
        Net Revenue
      </Header>
      <Grid className="ui two column grid">
        <Grid.Row>
          <Grid.Column>
            <Header as="h4" textAlign="left">
              YTD<Header sub>Year to Date</Header>
            </Header>
            <Statistic horizontal className="mini" floated="left">
              <Statistic.Value>91.9K</Statistic.Value>
              <Statistic.Label>Total</Statistic.Label>
            </Statistic>
            <Statistic horizontal className="mini lnegdot2em" floated="left">
              <Statistic.Value>321.8</Statistic.Value>
              <Statistic.Label>Daily Avg</Statistic.Label>
            </Statistic>
            <Statistic
              horizontal
              className="mini lnegdot2em unitmg"
              floated="left"
            >
              <Statistic.Value>321.8</Statistic.Value>
              <Statistic.Label>PER UNIT</Statistic.Label>
            </Statistic>
          </Grid.Column>
          <Grid.Column>
            <Header as="h4" textAlign="left">
              MTD<Header sub>Month to Date</Header>
            </Header>
            <Statistic horizontal className="ui mini" floated="left">
              <Statistic.Value>49.2K</Statistic.Value>
              <Statistic.Label>Total</Statistic.Label>
            </Statistic>
            <Statistic horizontal className="mini lnegdot2em" floated="left">
              <Statistic.Value>3.5K</Statistic.Value>
              <Statistic.Label>Daily Avg</Statistic.Label>
            </Statistic>
            <Statistic
              horizontal
              className="mini lnegdot2em unitmg"
              floated="left"
            >
              <Statistic.Value>321.8</Statistic.Value>
              <Statistic.Label>PER UNIT</Statistic.Label>
            </Statistic>
          </Grid.Column>
        </Grid.Row>
      </Grid>
    </Segment>
  </Segment.Group>
</div>

Вот фотография того, как будут выглядеть сегменты enter image description here

Я получил эту ошибку при попытке отфильтровать с помощью const YTD = this.state.data.filter(item => this.state.data.period === 'YTD'); и затем передать <ul><li>{this.state.data}</li></ul>


Objects are not valid as a React child (found: object with keys {period, sold, gross, cost, net, avgSold, avgGross, avgCost, avgNet, unitGross, unitCost, unitNet}). If you meant to render a collection of children, use an array instead.
    in li (at FetchTest.js:45)
    in ul (at FetchTest.js:44)
    in div (at FetchTest.js:37)
    in FetchTest (created by Context.Consumer)
    in withRouter(FetchTest) (created by Context.Consumer)
    in Route (at App.js:38)
    in div (at App.js:24)
    in Router (created by BrowserRouter)
    in BrowserRouter (at App.js:23)
    in App (at src/index.js:6)

1 Ответ

1 голос
/ 23 октября 2019

Этот ответ может быть не идеальным, но вы можете сделать это так.

{this.state.data.map(item => { 
 if (item.period === 'YTD') {
    Return <div>{item.gross}</div>
   }

Это пример использования карты для переформатирования объектов в массиве

Как в Mozilla https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...