这是密码。
import React, { Component } from "react";
import "./app.css";
import Header from "./components/header";
class App extends Component {
constructor(props) {
super(props);
this.state = {};
this.initState();
}
initState = () => {
this.getMostPopularVideos().then(result => {
this.setState({ contents: result });
console.log(result); // data is OK here.
});
}
getMostPopularVideos = async () => {
const requestOptions = {
method: 'GET',
redirect: 'follow'
};
const res = await fetch(<query path>, requestOptions)
let contents;
if (res.ok) {
contents = await res.json();
} else {
alert(`HTTP-Error: ${res.status}`);
contents = { a: { b: "test"}};
}
return contents;
}
render() {
console.log('render', this.props, this.state);
return (
<>
<Header/>
</>
);
}
}
export default App;代码从API中获取数据并将其分配给state。
但是在赋值之后,this.state是未定义的。
我试图在没有setState的情况下直接分配,结果是一样的。
有什么问题吗?
更新
我研究了React生命周期并更新了代码,这就是它。
import React, { Component } from "react";
import "./app.css";
import Header from "./components/header";
class App extends Component {
constructor(props) {
super(props);
this.state = {contents: null};
}
initState = () => {
this.getMostPopularVideos()
.then(result => this.setState({ contents: result }));
}
getMostPopularVideos = async () => {
const requestOptions = {
method: 'GET',
redirect: 'follow'
};
const res = await fetch(<query path>, requestOptions)
let contents;
if (res.ok) {
contents = await res.json();
} else {
alert(`HTTP-Error: ${res.status}`);
contents = { a: { b: "test"}};
}
return contents;
}
componentDidMount() {
this.initState()
}
render() {
console.log('render', this.props, this.state);
return (
<>
<Header/>
</>
);
}
}
export default App;我将异步逻辑移到componentDidMount()中,
但还是有问题。
检查人员说this.state包含我获取的数据,
console.log(this.state)语句在render()中-在第二次呈现后(因为setState)当我在铬控制台中输入console.log(this.state)后,它将返回undefined。
这种情况很奇怪。
有什么线索吗?
发布于 2021-01-23 00:32:46
我用占位符API尝试了修改后的代码如下:
const res = await fetch('https://jsonplaceholder.typicode.com/todos') 对我来说很管用。
要回答为什么在铬控制台中键入this.state时看不到它的值的问题:
如果您尝试在console中查看this.state的值,console.log(this.state),您将得到undefined,因为对于console,this将是全局window变量,它表示脚本正在运行的窗口,即:窗口对象
通过在console中执行this,您可以检查Window对象的值是否是console.log(this)。
https://stackoverflow.com/questions/65844741
复制相似问题