我正在尝试从Rest API“ TVMaze”获取数据。数据为json格式。我为此使用了react.js
这是我的myclass.js
文件
import React from "react";
import ReactDOM from "react-dom";
import axios from "axios";
function Myclass(){
return(
axios.get("http://api.tvmaze.com/schedule?country=US&date=2019-05-01")
.then (function(response){
console.log(response);
});
);
}
export default Myclass;
这是我的index.js
文件:
import React from "react";
import ReactDOM from "react-dom";
import Myclass from "./myclass.js";
import "./styles.css";
function App() {
return (
<Myclass/>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App/>, rootElement);
这是我收到的错误消息:
SyntaxError: /src/myclass.js: Unexpected token, expected "," (10:6)
src/myclass.js: Unexpected token, expected "," (10:6) 8 | .then (function(response){ 9 | console.log(response); > 10 | }); | ^ 11 | ); 12 | } 13 | 8 | .then (function(response){ 9 | console.log(response);
> 10 | }); | ^ 11 | ); 12 | } 13 |
browser
Parsing error: Unexpected token, expected "," 8 | .then (function(response){ 9 | console.log(response); > 10 | }); | ^ 11 | ); 12 | } 13 | (null)
eslint
答案 0 :(得分:0)
您的代码中有几个问题。 react组件必须返回要显示的内容(例如dom元素)或null
,但在这里您编写
Promise
return(
axios.get("http://api.tvmaze.com/schedule?country=US&date=2019-05-01")
.then (function(response){
console.log(response);
});
);
此外,您在then
和function
之间留有一个空格,这会引起错误。
当您想显示来自API请求的数据时,最好在componentDidMount
内调用API并将数据存储在组件的state
中。
您可以使用基于类的组件来实现:
import React from "react";
import axios from "axios";
class Myclass extends React.Component{
state = {data: null};
componentDidMount(){
axios.get("http://api.tvmaze.com/schedule?country=US&date=2019-05-01")
.then(function(response){
this.setState({data: response})
});
}
render(){
if(!this.state.data){
return null; //or a loading spinner or whatever
}
return data // here depending on the format of the data (array or object) you might need to do some process.
}
}
export default Myclass;
或带有钩子:
import React, {useEffect} from "react";
import axios from "axios";
const MyClass = function(){
const [data, setData] = useState(null);
useEffect(() => {
axios.get("http://api.tvmaze.com/schedule?country=US&date=2019-05-01")
.then(function(response){
setDate(response)
});
}, []) // with an empty array as a dependency, the API call will be run only once when the component is mounted.
if(!data){
return null;
}
return data // same comment than before to show your data properly
}
希望有帮助。
答案 1 :(得分:0)
您的myclass组件应如下所示。
import React ,{useEffect} from "react";
import ReactDOM from "react-dom";
import axios from "axios";
function Myclass(){
// The below useEffect is equivalent to a componentDidMount.
useEffect(()=>{
axios.get("http://api.tvmaze.com/schedule?country=US&date=2019-05-01")
.then (function(response){
console.log(response);
});
},[]);
return(
);
}
export default Myclass;