如何将响应识别为JSON?

时间:2016-11-12 06:27:26

标签: html

在我的ReactJS中,我正在获取API,而JSON正文响应字段如下:

{
"place": <a href=\"http:\/\/place.com\/
               search?q=%23MILKYDOG\" target=\"_blank\">#milkydog<\/a>
               and quickly came up with a little comic about it. You can
               (and should) follow Naomi on twitter <a href=\"http:\/\
               /david.com\/ngun\" target=\"_blank\">@ngun<\/a> "
}

当我尝试通过向下传递prop(fetched)来渲染它而不是识别格式和转义字符,并相应地渲染它们时。

2 个答案:

答案 0 :(得分:1)

这里发生的事情是,React通过不允许将随机HTML注入您的应用来帮助您。您需要使用注射内容的dangerouslySetInnerHTML方式。这是有目的的,因为React正在努力帮助您避免XSS攻击。因此,您必须以“危险”的方式执行此操作,以便考虑是否可以在不注入原始HTML的情况下执行此操作(看起来您可能从博客系统获取内容?可能是规则例外的一个很好的示例。 )

从React文档中,您可以使用以下内容:

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

e.g。在你的情况下

var fetchedFile = {
"body": `<p><img src=\"http:\/\/media.tumblr.com\
               /tumblr_lh6x8d7LBB1qa6gy3.jpg\"\/><a href=\"http:\/\
               /citriccomics.com\/blog\/?p=487\" target=\"_blank\">TO READ
               THE REST CLICK HERE<\/a><br\/>\n\nMilky Dog was inspired by
               something <a href=\"http:\/\/gunadie.com\/naomi\"
               target=\"_blank\">Naomi Gee<\/a> wrote on twitter, I really
               liked the hash tag <a href=\"http:\/\/twitter.com\/
               search?q=%23MILKYDOG\" target=\"_blank\">#milkydog<\/a>
               and quickly came up with a little comic about it. You can
               (and should) follow Naomi on twitter <a href=\"http:\/\
               /twitter.com\/ngun\" target=\"_blank\">@ngun<\/a> `
};


function createMarkup(html) {
  return {__html: html};
}

class MyThing extends React.Component {
  render() {
    return(
      <div dangerouslySetInnerHTML={createMarkup(fetchedFile.body)} />
    );
  }
}

ReactDOM.render(<MyThing />, document.getElementById('content'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>

<div id="content"></div>

答案 1 :(得分:0)

出于安全原因,默认情况下React总是呈现为javascript变量的textNode,除非您明确提及它。

render() {
    return(
        <div dangerouslySetInnerHtml={{__html: fetchedFile.body}} />
    )
}

详细了解here