Error converting string to JSON object in ReactJS application

As part of my ongoing ReactJS research efforts, I am developing a simple page that will display a list of trends as follows:

enter image description here

When you click the Get Trends button, the list of trends is retrieved from an external server via Web sites and displayed. It works as expected. Below is the corresponding source code:

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

class TrendRow extends Component {
  render() {
    return (
      <tr>
        <td>{this.props.onerow}</td>
      </tr>
    );
  }
}

class TrendTable extends Component {
  render() {
    var rows = [];
    for (var i=1; i<3; i++) {
      rows.push(<TrendRow key={i} onerow={this.props.trends[i]}/>);
    }
    return (
      <table>
        <thead>
          <tr>
            <th>List of Trends</th>
          </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
    );
  }
}

class App extends Component {
  constructor() {
    super();

    this.state = {
      ws: new WebSocket('ws://localhost:8025/websockets/TwitterWSService'),
      getTrendsqueryString: 'GETTRENDS',
      listoftrends: ['{"trend":"#Default","id":"0"}']
    };

    this.handleOnClick = this.handleOnClick.bind(this);
  }

  handleOnClick = (event) => {
    this.state.ws.send(this.state.getTrendsqueryString);
    this.state.ws.onmessage = (event) => {
      this.setState(prevState => ({listoftrends: prevState.listoftrends.concat(event.data)}));
    }
  }

  render() {
    return (
      <div>
          <button onClick={this.handleOnClick}>Get Trends</button>
          <TrendTable trends={this.state.listoftrends} />
      </div>
    );
  }
}

export default App;

Now, when I try to convert the JSON string being mapped to a JSON object using "JSON.parse", I get different types of errors based on where I parse it.

If I analyze as shown below,

class TrendRow extends Component {
  render() {
    var jsonobject = JSON.parse(this.props.onerow);
    return (
      <tr>
        <td>{jsonobject}</td>
      </tr>
    );
  }
}

I get the following error:

"SyntaxError: Unexpected token u in JSON at position 0

...

var jsonobject = JSON.parse (this.props.onerow);

... "

Google , , :

synaxerror U JSON

, , this this.props.onerow undefined JSON.parse() . "listoftrends" .

, , JSON.parse(), ,

  handleOnClick = (event) => {
    this.state.ws.send(this.state.getTrendsqueryString);
    this.state.ws.onmessage = (event) => {
      var jsonobject = JSON.parse(event.data);
      this.setState(prevState => ({listoftrends: prevState.listoftrends.concat(jsonobject)}));
    }
  }

:

React...

Google ! - ?

+4
5

( , ), , .

  • , this, , . , .

    this.handleOnClick = this.handleOnClick.bind(this);

  • for TrendTable map.

    class TrendTable extends Component { render() { return ( <table> <tbody>{this.props.trends.map(trend => <TrendRow key={i} onerow={trend}/>)} </tbody> </table> ); } }

    , , for.

  • trends componentDidMount recycle lifecycle. .

    , ( ), , ( , ).

  • , , state = {....}; . , 2.

, , :

class App extends Component {

  state = {
      ws: new WebSocket('ws://localhost:8025/websockets/TwitterWSService'),
      getTrendsqueryString: 'GETTRENDS',
      listoftrends: [] // you can add default trend record if you need it
    };
  };

  componentDidMount() {
    this.fetchTrends();
  }

  fetchTrends = (completeUpdate = false) => { 
    this.state.ws.send(this.state.getTrendsqueryString);
    this.state.ws.onmessage = (event) => {
      this.setState(prevState => (
        { listoftrends: !completeUpdate ? prevState.listoftrends.concat(event.data) : event.data }
      ));
    }    
  };

  updateTrends = () => {
    this.fetchTrends(true); //in that case you'd like to completely update the list
  }

}
  render() {
    return (
      <div>
        <button onClick={this.updateTrends}>Update trends</button>
        <TrendTable trends={this.state.listoftrends} />
      </div>
    );
  }
}
  1. . , , JSX, (, ).

.

var array = Object.values(jsonobject).map(value => ...);

// and then in JSX
<div>{array}</div>

, .

+3

jsonobject - .

, .

.

var jsonArray = Object.keys(jsonobject).map(function(k) {
  return jsonobject[k];
});

JSX:

<td>{jsonobject}</td>

+1

, , JSON :

var jsonobject = this.props.onerow ? JSON.parse(this.props.onerow) : {};

, . <td>{jsonobject}</td> <td>{jsonobject.id}</td>.

+1

JSON,

console.log(this.props.onerow);
console.log(JSON.parse(this.props.onerow));

? , , , "JSON" , , , - , JSON.parse , .

Objects are not valid as a React child - , JSX, :

render(){
    let someObj = {potato:1, hello:'hi there'};
    return(<div>Here the object: {someObj}</div>); <-- ERROR! can't put an object here
}

, , - JSON JSX.

0

, . , , .

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

class TrendRow extends Component {
  render() {
    var jsonArray = Object.keys(this.props.onerow).map((k) => {
                                                  return this.props.onerow[k];
                                                  });
    return (
      <tr>
        <td>{jsonArray[0]}</td>
      </tr>
    );
  }
}

class TrendTable extends Component {
  render() {
    var rows = this.props.trends.map((trend, index) => {
          return (index<2) ? <TrendRow key={index} onerow={trend} /> : [];
        }
      );

    return (
      <table>
        <thead>
          <tr>
            <th>List of Trends</th>
          </tr>
        </thead>
        <tbody>{rows}</tbody>
      </table>
    );
  }
}

class App extends Component {
  constructor() {
    super();

    this.state = {
      ws: {},
      getTrendsqueryString: 'GET',
      listoftrends: []
    };
  }

  componentDidMount = () => {
    this.setState({ws: new WebSocket('ws://localhost:8025/websockets/TwitterWSService')});
  }

  handleOnClick = (event) => {
    this.state.ws.send(this.state.getTrendsqueryString);
    this.state.ws.onmessage = (event) => {
      var jsonobject = JSON.parse(event.data);
      this.setState(prevState => ({listoftrends: prevState.listoftrends.concat(jsonobject)}));
    }
    this.state.ws.onclose = (event) => {
      this.setState({ws: new WebSocket('ws://localhost:8025/websockets/TwitterWSService')});
    }
  }

  render() {
    return (
      <div>
          <button onClick={this.handleOnClick}>Get Trends</button>
        <TrendTable trends={this.state.listoftrends} />
      </div>
    );
  }
}

export default App;
0

Source: https://habr.com/ru/post/1685300/


All Articles