📜  在 react 中更改 api fetch onclick - CSS 代码示例

📅  最后修改于: 2022-03-11 14:47:55.685000             🧑  作者: Mango

代码示例1
class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      isLoading: false,
      results: [],
      error: null,
    };
  }

  fetchData = (url, query, key) => {
    fetch(`the/api/${url}${query}.json?api-key${key}`)
      .then(res => res.ok && res.json())
      .then(data => this.setState({ results: data.results, isLoading: false }))
      .catch(error => this.setState({ error, isLoading: false }));
  }

  componentDidMount() {
    fetchData('api_url', 'all', 'key_here');
  }

  handleCategory = (e) => {
    const cat = e.target.getAttribute('data-facet');
    fetchData('api_url', cat, 'key_here');
  }

  render() {
    const { isLoading, results, error } = this.state;

    if (isLoading) {
      return 
} if (error) { return
} return (
{results.map(res => ...)}
); } }