字符串prop传递给来自父级的子组件 - 无法使用JSON.parse()转换为Object

时间:2016-06-13 13:34:06

标签: javascript json ajax reactjs jsx

问题摘要:

  

React组件SLTree读取(ajax)一个JSON,转换为字符串和   将其作为财产传递给两个包含的'组件 - 编辑和   TNODE。编辑器组件(封装CodeMirror)工作正常,但是   收到的属性的JSON.parse()之后的TNode组件事件   保持将返回的对象解释为字符串,而不是Object。

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:

  • 父级:SLTree(使用JQuery ajax读取JSON以上)
  • 孩子:编辑 - 工作正常)
  • TNode - 如果传递了字符串属性,则无法“对象”。
    • JSON.parse(prop-pass-by-parent)
    • JSON.parse(JSON.stringify(prop-pass-by-parent)) - 一些答案 stackoverflow建议在解析之前使用显式stringify

某些引用指示在解析之前显式执行stringify。 所以我也试过了:

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

父组件的代码 - 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>
    )
  }
});

编辑器组件正常工作。

  

下面的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>
    );
  }
});

以下是示例控制台日志 - 请注意节点&#39;节点&#39;被解释为字符串,而不是对象。请注意,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)

1 个答案:

答案 0 :(得分:1)

我认为问题可能来自这条线:

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

当您的前端从此行的AJAX调用接收数据时,它已经是JSON.stringified。通过再次对其进行字符串化,您将添加另一对引号,这意味着在解析它时,它只会删除该对,但不会将其解析回对象。

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

这会将displayText设置为字符串化的JSON。然后,您需要在子组件中解析它。

你也可以这样做:this.setState({displayText: JSON.parse(data)});

在这种情况下,数据将被解析并作为对象存储在状态中,并且应该可以访问所有子组件。