简体   繁体   English

将字符串转换为 JSON 或 Javascript/React 中的其他数据结构

[英]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 .这就是this.props.data样子

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:例如,如果在render()中添加:

console.log(typeof data) -> returns string console.log(typeof data) -> 返回string

So I tried to convert it to JSON:所以我尝试将其转换为 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. React 无法访问开发中的实际错误 object。

Is it something wrong with the format of this.props.data ? this.props.data的格式有问题吗? How can I convert it from string to other data structure?如何将其从字符串转换为其他数据结构? (because I need to performs map and reduce on it). (因为我需要执行mapreduce它)。

First of all your Table component requires a return statement.首先,您的 Table 组件需要一个 return 语句。 However regarding the original question, I'm suspecting your api is return something different from your expected response.但是,关于原始问题,我怀疑您的 api 返回的内容与您的预期响应不同。 I created a.json file with your expected data, imported data in App, and rendered Table inside app.我使用您的预期数据创建了一个.json 文件,在应用程序中导入数据,并在应用程序内呈现表格。

Whats the result when you console log data in Table component.当您在 Table 组件中控制台日志数据时,结果是什么。

App.js应用程序.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表.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>
        );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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