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

标签 javascript reactjs callback

我有一个输入框,它从 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/

相关文章:

javascript - observableArray 和 foreach 绑定(bind)的内存泄漏

javascript - 如何将 Tradingview js 注入(inject) React Typescript 渲染函数?

reactjs - Formik 未捕获类型错误 : Cannot read property 'getFieldProps' of undefined

javascript - 异步队列,文件流结束如何知道两者何时完成

C++设置回调函数

javascript - 是否可以在 Javascript 的 Split Regexp 中连接变量?例如 : var. split(/[A-Z]/+ 变量 +/\d/);

javascript - youtube api 视频结束加载函数

javascript - 将数据从 Controller 传递到 javascript(绕过 View )

javascript - react : how to update states which have both mutable and immutable values

JavaScript 对象文字 "this"关键字 jQuery 回调参数传递