@kashcheev

Возможно ли вывести выхлоп xml-js в componentDidMount?

Здравствуйте!

Подскажите, пожалуйста, как "подружить" две конструкции:

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    }
  }

componentDidMount() {
    const url = "";
    fetch(url)
    .then(response => response.json())
    .then(json => this.setState({ posts: json }))
  }

  render() {
    const { posts } = this.state;
    return (
      <div className="container">
        {posts.map((post) => (
          <div className="card" key={post.id}>
              #{post.id} {post.title}
              <p className="text">{post.body}</p>
          </div>
        ))}
      </div>
    );
  }
}


var convert = require('xml-js');
var xml =
'<?xml version="1.0" encoding="utf-8"?>' +
'<note importance="high" logged="true">' +
'    <title>Happy</title>' +
'    <todo>Work</todo>' +
'    <todo>Play</todo>' +
'</note>';
var result1 = convert.xml2json(xml, {compact: true, spaces: 4});
var result2 = convert.xml2json(xml, {compact: false, spaces: 4});
window.alert(result1, '\n', result2);


Возможно ли выхлоп result1, '\n', result2 поместить внутрь componentDidMount() вместо значения url, где сейчас ссылка на json?

p.s.
React ковыряю из интереса, опыт работы с JS небольшой.
Google отличный наставник, но конкретных примеров по ситуации я не нашел.

p.s.s.
Интересно решение именно средствами js, понятно, что на руках чаще всего есть нормальный json.
  • Вопрос задан
  • 160 просмотров
Решения вопроса 1
RomReed
@RomReed
JavaScript, Flutter, ReactNative, Redux, Firebase
componentDidMount() {
    const result1 = convert.xml2json(xml, { compact: true, spaces: 4 });
    const data =  JSON.parse(result1);
    this.setState({ posts: data })
  }
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы