我将状态设置为空数组,然后调用函数来更新组件的状态。当我记录函数的状态时,我同时获取空数组和更新后的数组。
发生这种情况的任何原因以及如何仅记录更新的状态。
以下是我的代码:
class App extends Component {
constructor(props) {
super(props);
this.state = {
videos: [],
};
YTSearch({ key: API_Keys, term: 'USA Top40' }, (videos) => {
this.setState({ videos });
});
}
render() {
return (
<div>
<SearchBar />
{console.log(this.state)}
</div>
)
}
}
这是控制台.log
最佳答案
您不应该在 render
方法中返回 console.log
!
您的代码最好是:
class App extends Component {
constructor(props) {
super(props);
this.state = { videos: [] };
}
componentDidMount() {
YTSearch({ key: API_Keys, term: 'USA Top40' }, (videos) => {
this.setState({ videos });
});
}
componentDidUpdate(prevProps, prevState) {
const { videos } = this.state;
if(prevState.videos !== videos) {
console.log(videos);
}
}
render() {
return (
<div>
<SearchBar />
</div>
)
}
}
此外,您可以将 console.log
放在 return 之外:
render() {
console.log(this.state);
return (
<div>
<SearchBar />
</div>
)
}
关于javascript - 记录类组件的状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52575287/