gpt4 book ai didi

javascript - 我可以在控制台中看到数据,但无法获取它。 React 中的父子回调

转载 作者:行者123 更新时间:2023-11-30 21:09:52 25 4
gpt4 key购买 nike

我有一个输入框,它从 youtube API 中提取数据并输出。到目前为止,我在输入结果时看到的是 Json,但我无法获取任何数据。

父组件

import Searching from "./Searching";

class App extends Component {
// constructor(props){
// super(props);

// this.state = {
// applications: ""
// }
// }

yourCallback(searchResults) {
console.log("searchResults", searchResults);
}

render() {
// console.log ('this.props', this.props)
return (
<div className="App">
<Searching
callback={this.yourCallback}
/>
<br/>
<h1>{this.searchResults}</h1>
</div>
);
}
}

export default App;

所以,在控制台中我看到:

enter image description here

理想情况下,我需要创建一个 SearchItem 组件,然后传递一个包含来自此 API 的数据的属性,例如 videoId 或其他内容。但是,我需要看到我可以从中获取数据并在 div 或 h1 标签内输出。我做错了什么?即使我可以在控制台中看到它,我也无法获取这些数据。

最佳答案

只需在父组件中管理一个 state 并在回调中设置该状态,如下所示:

class App extends Component {
constructor(props){
super(props);
// Maintain a state
this.state = {
searchResults: ""
}
// Bind yourCallback like this
this.yourCallback = this.yourCallback.bind(this);
}

yourCallback(searchResults) {
console.log("searchResults", searchResults);
// set the state with the result
this.setState({searchResults});
}

render() {
// console.log ('this.props', this.props)
return (
<div className="App">
<Searching
callback={this.yourCallback}
/>
<br/>
// Show that state
{
this.state.searchResults
? this.state.searchResults.map((r) =>
<h1>{r.id.videoId}</h1>) : null;
</div>
);
}
}

关于javascript - 我可以在控制台中看到数据,但无法获取它。 React 中的父子回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46267649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com