React JS-componentDidMount()代码是否以JavaScript发送到客户端浏览器?

时间:2018-09-01 03:07:33

标签: javascript html reactjs

我是reactjs的新手,正在边做边学... 像html文件中的其他JavaScript一样,将componentDidMountt()中的代码发送到客户端浏览器?我担心,因为我将在componentDidMount()中使用api的url调用fetch。还是代码全部保留在服务器中,而只有虚拟Dom和真实Dom之间的更改被转移到了客户端浏览器,而没有任何js?

2 个答案:

答案 0 :(得分:0)

通常,是的,尽管从技术上讲,React不参与设置的那一部分,但是所有React组件(包括其代码)都将发送到客户端(浏览器)。

通常,您不希望将任何机密发送给客户端,而是依靠您控制的后端代码来访问机密并对第三方API进行必要的调用。借助AWS Lambda等无服务器设置,您甚至无需运行服务器即可完成此工作。

答案 1 :(得分:0)

实际上,它可以...例如,当组件安装在该代码中时,可以从youtube获取数据。...

class App extends React.Component {  
  constructor (props) {
    super(props);
    this.state = {
      videos: [],
      currentVideo: null
    };
  }
  
  componentDidMount() {
    this.fetchYouTube('learn javascript');
  }
  
  fetchYouTube (query) {
    let options = {
      query: query,
      key: YOUTUBE_API_KEY
    };
    this.props.searchYouTube(options, (videos) => {
      this.setState({
        videos: videos, 
        currentVideo: videos[0]
      });
    });
  }
  
  handleVideoClick (video) {
    this.setState({
      currentVideo: video
    });
  } 
  
  render () { 
    return (
    <div>
      <Nav handleSearchChange={_.debounce((input) => this.fetchYouTube(input), 500)} />
      <div className="col-md-7">
        <VideoPlayer video={ this.state.currentVideo } />
      </div>
      <div className="col-md-5">
        <VideoList videos={ this.state.videos } listClick={this.handleVideoClick.bind(this)} />
      </div>
    </div>
    );
  }
}

// In the ES6 spec, files are "modules" and do not share a top-level scope
// `var` declarations will only exist globally where explicitly defined
window.App = App;