简体   繁体   中英

Convert string into JSON or other data structure in Javascript/React

The data comes as props from the parent component:

  render() {
    return (
      <div className='App'>
        <header className='App-header'>
          <Table data={this.state.apiResponse} />
        </header>
      </div>
    );
  }

and the Table component is below. If the data is sent like this is is sent to render as a whole, it is shown on the screen. This is how this.props.data looks like .

class Table extends React.Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { data } = this.props;
      <div>
        <table>
          <thead>
            <tr>{data}</tr>
          </thead>
        </table>
      </div>
    );
  }
}

export default Table;

The problem appears when I want to modify that data. For example, if in render() is added:

console.log(typeof data) -> returns string

So I tried to convert it to JSON:

const convertedData = JSON.parse(data); -> returns error message:

Error: A cross-origin error was thrown. React doesn't have access to the actual error object in development.

Is it something wrong with the format of this.props.data ? How can I convert it from string to other data structure? (because I need to performs map and reduce on it).

First of all your Table component requires a return statement. However regarding the original question, I'm suspecting your api is return something different from your expected response. I created a.json file with your expected data, imported data in App, and rendered Table inside app.

Whats the result when you console log data in Table component.

App.js

import React from 'react';
import './App.css';
import apiData from './api'
import Table from "./Table";

function App() {
     return (
        <div className="App">
             <header className="App-header">
                   <Table data={apiData} />
             </header>
        </div>
     );
}
export default App;

Table.js

import React, {PureComponent} from "react";

export default class Table extends PureComponent{

    render() {
        const { data } = this.props;
        return(
            <div>
                <table>
                    <thead>
                         <tr>{data[0].game_id} {typeof data}</tr>
                    </thead>
                </table>
            </div>
        );
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM