在函数内获取请求。怎么放在ComponentDidMount里面呢?

Fetch request inside function. How to put it in ComponentDidMount?

如您所见,我的 handleSearchRequest 函数正在调用 API ,稍后由 IconButton 标记内的 onClick 事件调用。

如何在 ComponentWillMount 中加载 API,这样我仍然可以在 HandleSearchRequest 上写东西,比如 setState 之类的,这样 Onclick 仍然可以调用这个函数?

class Searcher extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      query: '',
      application: null
    }

  }

  // componentDidMount () {
  //
  //
  //
  // }

  handleSearchRequest() {
    console.log('this.state', this.state);
    const BASE_URL = 'https://itunes.apple.com/search?term';
    const FETCH_URL = BASE_URL + '=' + this.state.query;
    console.log('FETCH_URL', FETCH_URL);

    fetch(FETCH_URL, {
      method: 'GET'
    })

      .then(response => response.json())
        .then(json => {
          const application = json.results[0];
          this.setState({application})
          console.log({application})
        });
  }

  render () {
    return (
      <div style={{position: 'relative'}}>
           <IconButton
             iconStyle={styles.smallIcon}
             style={styles.iconButton}
             onClick={() => this.handleSearchRequest()}
           >
               <Search color={black} />
           </IconButton>
        <TextField
          underlineShow={false}
          id="searchId"
          value={this.state.query}
          fullWidth={true}
          style={styles.textField}
          inputStyle={styles.inputStyle}
          hintStyle={styles.hintStyle}
          onChange={event => {this.setState({ query: event.target.value}) }}
          onKeyPress={event => {
            if (event.key === 'Enter') {
              this.handleSearchRequest()
            }
          }}
        />
        <br/>
        <br/>
        {
          this.state.application !== null
          ?
            <ResultItem
              {...this.props} {...this.state}
              application={this.state.application}
            />
          : <div></div>
        }
      </div>
    );
  }
}
export default Searcher;

编辑

这是 ResultItem 组件

class ResultItem extends Component {

componentDidMount () {

}
  render () {
    // console.log ('myProps', this.props);

    let application = {
      artistName: '',
      country: '',
      primaryGenreName: '',
      trackName: ''
    };

    if (this.props.application !== null) {
      application = this.props.application
    }

    return (
      <div>

        <Card style={{width:'30%'}}>
          <CardMedia>
            <div style={styles.appCard}/>
          </CardMedia>
          <FloatingActionButton
            style={styles.addButton}
            backgroundColor={'#CC0000'}
            >
            <ContentAdd />
          </FloatingActionButton>
          <CardTitle
            title={application.artistName}
                     subtitle="Application" />
          <CardText>
            <div>
              <div>Name:   <b>{application.artistName}      </b> </div>
              <div>Country:<b>{application.country}         </b> </div>
              <div>Genre:  <b>{application.primaryGenreName}</b> </div>
              <div>Song:   <b>{application.trackName}       </b> </div>
            </div>
          </CardText>
        </Card>
    </div>
    );
  }
}

export default ResultItem; 

生命周期方法 componentDidMount 通常用于获取一些初始数据供 React 组件使用。

给定一个方法,该方法发出 HTTP 请求以获取一些数据。例如,

fetchData() {
  fetch('https://www.somewhere.com/someResource')
    .then(response => response.json())
    .then(responseJson => {
      this.setState({ someResource: responseJson });
    });
}

获取数据后,您可以使用 setState() 将数据保存到组件状态中,如上所示。

然后简单地从 componentDidMount() 调用它以使用初始数据填充您的组件状态:

componentDidMount() {
  this.fetchData();
}

您可以随时再次调用 fetchData() 再次获取该数据。

要从任何组件方法(如在 render() 中)访问资源,请使用 this.state.someResource

更新:

如果您的组件依赖于数据进行自身渲染,那么您应该小心了。最初不会有数据,因此如果组件依赖于该数据,则不应呈现该组件,如果它不存在,则会报错。

解决方案是在渲染任何内容之前检查数据是否存在。

例子

render() {
  if (!this.props.someResource) {
    // resource is not yet loaded
    return <div>Loading resource...</div>;
  }

  // Otherwise, if someResource has been fetched (i.e. is not undefined)
  // You can safely render the component that is dependent on it
  return (
    <MyComponent someResource={this.props.someResource} />
  );
}