简体   繁体   English

传递了字符串属性以响应父级的子级组件-无法使用JSON.parse()转换为Object

[英]String prop passed to react child component from parent - unable to conver to Object with JSON.parse()

Problem Summary: 问题摘要:

React component SLTree reads (ajax) a JSON, converts to string and passes it as property to two 'contained' components - Editor and TNode. React组件SLTree读取(ajax)JSON,转换为字符串并将其作为属性传递给两个“包含”的组件-Editor和TNode。 Editor component (which encapsulates CodeMirror) works OK, but the TNode component event after JSON.parse() of the received property keeps interpreting the returned object as a string, instead of Object. 编辑器组件(封装了CodeMirror)可以正常工作,但是接收到的属性的JSON.parse()之后的TNode组件事件始终将返回的对象解释为字符串,而不是Object。

JSON file (validated): JSON文件(已验证):

"x":  {
            "id": 1,
            "content": "Hello, world!\n"
        },
"y":  {
            "id": 2,
            "content": "React is awesome.\n"
        },
"z":  {
            "id": 3,
            "content": "Robots are pretty cool.\n"
        },
"l":  {
            "id": 4,
            "content": "Monkeys.\nWho doesn't love monkeys?\n"
        }
}

React Components: 反应组件:

  • Parent: SLTree (reads above JSON using JQuery ajax) 父级:SLTree(使用JQuery ajax在JSON之上读取)
  • Child: Editor - works correctly) 子级:编辑器-正常工作)
  • TNode - fails to 'Object'ify the passed string property. TNode-无法“对象化”传递的字符串属性。
    • JSON.parse(prop-passed-by-parent) JSON.parse(父母双方传递)
    • JSON.parse(JSON.stringify(prop-passed-by-parent)) - some answers on stackoverflow suggest using explicit stringify, before parse JSON.parse(JSON.stringify(prop-passed-by-parent))-关于堆栈溢出的一些答案建议在解析之前使用显式stringify

Some reference indicated explicitly doing a stringify before parse. 一些参考指出在解析之前明确地进行了字符串化。 So I also tried: 所以我也尝试了:

let expectObj_gettingString = JSON.parse(JSON.stringify(this.props.node))

Code for parent component - SLTree: 父组件的代码-SLTree:

import Editor from './Editor.jsx';
import TNode from './TNode.jsx';    
var $ = require('jquery');
const lstyle = {
  border: "solid navy 1px"
}
export default React.createClass({

  getInitialState: function() {
    return {
      displayText: ''
    }
  },
  componentDidMount: function() {
    this.serverRequest = $.ajax({
      url: "./sltree/sample.json",
      dataType: 'json',
      cache: false,
      success: function(data) {
        console.log(data);
        this.setState({displayText: JSON.stringify(data, null, ' ')});
      }.bind(this),
      error: function(xhr, status, err) {
        // console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  componentWillUnmount: function() {
    this.serverRequest.abort();
  },
  render() {
    return (
      <div className="row">
        <div style={lstyle} className="col-lg-6 col-md-6 col-sm-6 col-xs-6">
          <Editor displayText={this.state.displayText} />
        </div>
        <div style={lstyle} className="col-lg-6 col-md-6 col-sm-6 col-xs-6">
          <TNode node={this.state.displayText} />
        </div>
      </div>
    )
  }
});

Editor component works correctly. 编辑器组件正常工作。

TNode component below fails to convert this.props.node to a JSON object - and keeps interpreting it as a string - as evident from console logs below and display on the browser (not shown here) 下面的TNode组件无法将this.props.node转换为JSON对象-并继续将其解释为字符串-从下面的控制台日志中可以看到并显示在浏览器上(此处未显示)

import React from 'react';
import ReactDOM from 'react-dom';
var $ = require('jquery');

export default React.createClass({
  render() {
    let n = this.props.node;
    console.log("node type:("+ typeof n + ")")
    let s = "";
    for (var k in n) {
      s += k + " : " + n[k] + " : typeof n[k]("+typeof n[k]+")\n";
      console.log(s);
    }
    return (
      <div>{s}</div>
    );
  }
});

Here's the sample console log - note how 'node' is interpreted as string, instead of object. 这是示例控制台日志-请注意如何将“节点”解释为字符串而不是对象。 Note that index(key) is integer and value is character in the string. 请注意,index(key)是整数,而value是字符串中的字符。

    node type:(string)
bundle.js:70 document ready in sltree/main.js: dependencies loaded.
bundle.js:20470 Object {x: Object, y: Object, z: Object, l: Object}l: Objectcontent: "Monkeys.↵Who doesn't love monkeys?↵"id: 4__proto__: Objectx: Objectcontent: "Hello, world!↵"id: 1__proto__: Objecty: Objectz: Object__proto__: Object
bundle.js:41476 node type:(string)
bundle.js:41480 0 : { : typeof n[k](string)

bundle.js:41480 1 : 
 : typeof n[k](string)

bundle.js:41480 2 :   : typeof n[k](string)

bundle.js:41480 3 : " : typeof n[k](string)

bundle.js:41480 4 : x : typeof n[k](string)

bundle.js:41480 5 : " : typeof n[k](string)

bundle.js:41480 6 : : : typeof n[k](string)

bundle.js:41480 7 :   : typeof n[k](string)

bundle.js:41480 8 : { : typeof n[k](string)

bundle.js:41480 9 : 
 : typeof n[k](string)

bundle.js:41480 10 :   : typeof n[k](string)

bundle.js:41480 11 :   : typeof n[k](string)

bundle.js:41480 12 : " : typeof n[k](string)

bundle.js:41480 13 : i : typeof n[k](string)

bundle.js:41480 14 : d : typeof n[k](string)

bundle.js:41480 15 : " : typeof n[k](string)

bundle.js:41480 16 : : : typeof n[k](string)

bundle.js:41480 17 :   : typeof n[k](string)

bundle.js:41480 18 : 1 : typeof n[k](string)

bundle.js:41480 19 : , : typeof n[k](string)

bundle.js:41480 20 : 
 : typeof n[k](string)

bundle.js:41480 21 :   : typeof n[k](string)

bundle.js:41480 22 :   : typeof n[k](string)

bundle.js:41480 23 : " : typeof n[k](string)

bundle.js:41480 24 : c : typeof n[k](string)

bundle.js:41480 25 : o : typeof n[k](string)

bundle.js:41480 26 : n : typeof n[k](string)

bundle.js:41480 27 : t : typeof n[k](string)

bundle.js:41480 28 : e : typeof n[k](string)

bundle.js:41480 29 : n : typeof n[k](string)

bundle.js:41480 30 : t : typeof n[k](string)

bundle.js:41480 31 : " : typeof n[k](string)

bundle.js:41480 32 : : : typeof n[k](string)

bundle.js:41480 33 :   : typeof n[k](string)

bundle.js:41480 34 : " : typeof n[k](string)

bundle.js:41480 35 : H : typeof n[k](string)

bundle.js:41480 36 : e : typeof n[k](string)

bundle.js:41480 37 : l : typeof n[k](string)

bundle.js:41480 38 : l : typeof n[k](string)

bundle.js:41480 39 : o : typeof n[k](string)

bundle.js:41480 40 : , : typeof n[k](string)

bundle.js:41480 41 :   : typeof n[k](string)

bundle.js:41480 42 : w : typeof n[k](string)

bundle.js:41480 43 : o : typeof n[k](string)

bundle.js:41480 44 : r : typeof n[k](string)

bundle.js:41480 45 : l : typeof n[k](string)

I think the problem may come from this line: 我认为问题可能出在这行:

this.setState({displayText: JSON.stringify(data, null, ' ')});

When your frontend receives the data from the AJAX call on this line, it has already been JSON.stringified. 当前端在此行上从AJAX调用接收到数据时,它已经被JSON.stringified了。 By stringifying it again, you are adding another pair of quotation marks, which means that when you parse it, it only removes that pair, but doesn't parse it back into an object. 通过再次对其进行字符串化,您将添加另一对引号,这意味着在解析它时,它只会删除该对,而不会将其解析回一个对象。

Try: this.setState({displayText: data}); 试试: this.setState({displayText: data});

This will set displayText to be the stringified JSON. 这会将displayText设置为字符串化的JSON。 You will then need to parse it in the child component. 然后,您将需要在子组件中对其进行解析。

You could also do: this.setState({displayText: JSON.parse(data)}); 您也可以这样做: this.setState({displayText: JSON.parse(data)});

In which case the data will be parsed and stored in state as an object, and should be accessible as it is to all child components. 在这种情况下,数据将被解析并作为对象存储在状态中,并且所有子组件都应可以访问。

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

相关问题 将道具从孩子传递给父母不工作(反应) - Passed prop from child to parent not working (React) React - 使用从父组件传递的道具渲染子组件时出错 - React - Error while rendering child component with prop passed from parent component React中从父组件传递给子组件的“未定义”? - 'Undefined' passed from parent to child component in React? 从父组件传递道具在子组件 React 中变为空 - Passing a prop from a Parent component becomes null in the Child component React React-Router-Dom v5.2,无法将道具从父级收到的道具传递给子组件 - React-Router-Dom v5.2 , unable to pass props to a child component from prop recieved by parent 反应状态作为道具传递给子组件未显示 - React state passed as prop to child component not showing 使用 React Hooks,当我将 prop 从父组件传递给子组件时,子组件中的 prop 未定义 - Using React Hooks, when I pass down a prop from parent to a child component, the prop in the child component is undefined 无法加载通过 React App 中的父组件作为道具传递给子组件的图像 - Can't load images passed on to a child component as a prop by parent component in a React App JSON.parse无法从字符串创建对象 - JSON.parse fails to create an object from a string JSON.parse用于JSON对象而不是字符串 - JSON.parse for JSON object instead of a string
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM