我是React的新手,在我非常简单的应用程序中,我只是想读取并显示一个json数据(他们发布的公司和工作)。使用React 16.3.0和react-dom 16.3.2和axios 0.18.0
我的代码在下面,最终输出应该以一种漂亮的格式显示我试图在每一行中获取的数据。
但它根本没有呈现并且出错 - 我必须在这里做一些非常愚蠢的错误。
Uncaught (in promise) TypeError: Cannot read property 'protocol' of undefined
at isURLSameOrigin (isURLSameOrigin.js:57)
at dispatchXhrRequest (xhr.js:109)
at new Promise (<anonymous>)
at xhrAdapter (xhr.js:12)
at dispatchRequest (dispatchRequest.js:59)
这是我的代码,这里是jsfiddle
<!-- DOCTYPE HTML -->
<html>
<head>
<title>Your First React Project</title>
<link rel="stylesheet" type="text/css" href="app.css">
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.26.0/babel.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
class App extends React.component {
constructor (props) {
super(props);
this.state = { jobs: [] };
}
componentDidMount () {
// var th = this;
this.serverRequest =
axios.get(this.props.source)
.then(function(result) {
this.setState({
jobs: result.data.jobs
});
})
}
componentWillUnmount () {
this.serverRequest.abort();
}
render () {
return (
<div>
<h1>Jobs!</h1>
{/* Don't have an ID to use for the key, URL work ok? */}
{this.state.jobs.map(function(job) {
return (
<div key={job.url} className="job">
<a href={job.url}>
{job.company_name}
is looking for a
{job.term}
{job.title}
</a>
</div>
);
})}
</div>
)
}
}
ReactDOM.render(<App source="https://gist.githubusercontent.com/rohan-paul/b74bf6ef1adfdb92e0af5783e6c93a71/raw/bdffbbcb50128c03dd9edc90dbeb85e88c70ebc4/jobs.json"/>, document.getElementById('#root'));
</script>
</body>
</html>
答案 0 :(得分:2)
这里有固定的jsfiddle:https://jsfiddle.net/n85v504b/2/
问题是你正在制作交叉原始请求,默认情况下不允许这样做。我已将axios电话改为:
new OptimizeCSSPlugin({
cssProcessorOptions: {
safe: true
}
}),
同时更改了promise fullfillment,因为这是未定义的(原因在此处解释Why is "this" in an anonymous function undefined when using strict?)
axios.request({
method: "get",
url: this.props.source,
crossDomain: true
})