简单的ReactJS代码无效

时间:2017-09-28 00:59:16

标签: javascript reactjs

以下Simple ReactJS代码无效。新手需要帮助!

<html lang="en">
<head>
<meta charset="UTF-8">
<title>ReactJS Test</title>
<script crossorigin src="https://unpkg.com/react@16/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/babel-standalone@6.15.0/babel.min.js"></script>
</head>
<body>
<div id="container"></div>

<script type="text/babel">
var currentLocation = window.location;
ReactDOM.render(
        <div>
            <p>currentLocation : {currentLocation}</p>
        </div>,
    document.getElementById('container')
);
</script>
</body>
</html>

Chrome控制台显示无助的错误消息,如下所示:

react-dom.production.min.js:67 Uncaught Error: Minified React error #31; visit http://facebook.github.io/react/docs/error-decoder.html?invariant=31&args[]=http%3A%2F%2Fxxxxxxx.com%3A8080%2F_test%2Fsitetest_new.jsp&args[]= for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
    at m (react-dom.production.min.js:67)
    at qb (react-dom.production.min.js:82)
    at z (react-dom.production.min.js:87)
    at C (react-dom.production.min.js:89)
    at react-dom.production.min.js:94
    at g (react-dom.production.min.js:43)
    at f (react-dom.production.min.js:43)
    at beginWork (react-dom.production.min.js:48)
    at e (react-dom.production.min.js:18)
    at k (react-dom.production.min.js:19)

提前致谢!

1 个答案:

答案 0 :(得分:2)

window.location返回一个对象。您无法在JSX中嵌入独立对象。您只能嵌入JavaScript expressions

尝试使用JSON.stringify()将对象转换为字符串。

您可以在下方运行该代码段或查看 CodePen Demo

&#13;
&#13;
var currentLocation = window.location;

ReactDOM.render(
        <div>
            <p>currentLocation : {JSON.stringify(currentLocation)}</p>
        </div>,
    document.getElementById('container')
);
&#13;
<div id="container"></div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;
&#13;
&#13;

注意:如果您只想要window.location对象中的字符串值(例如href),则不需要JSON.stringify()

您可以直接在JSX中使用window.location.href(或设置var currentLocation = window.location.ref;) - example