简体   繁体   English

如何在 React 中单击按钮时从服务器转储数据?

[英]How to dump data from server on button click in React?

I am trying to fetch data from the server via the fetch function.我正在尝试通过 fetch 函数从服务器获取数据。 But I need this data to be displayed after these buttons.但是我需要在这些按钮之后显示这些数据。 Without the button, the data is displayed.如果没有按钮,则显示数据。 Here is my code:这是我的代码:

import React, {Component} from "react";
export default class Ccomponent extends Component{
  constructor(props){
    super(props);
    this.state = {
      items: [], index: ''
    };
  }

  componentDidMount(){
    fetch("https://jsonplaceholder.typicode.com/users")
    .then(res => res.json())
    .then(
      (result) => {
        this.setState({
          items: result
        });
      }
    )



  }

  render(){
    const {items} = this.state;
    return(
<div>
<button key={index}
      onClick={() => {
      {items.map(item => (
        <blockquote>
        <i key={item.name}>
        Name: </i> {item.name};

        </blockquote>
      ))}
    }}>klik</button>

</div>
    )
  }
}

Transfer that function from componentDidMount and just add the fetch function to an onClick function从 componentDidMount 传输该函数,然后将 fetch 函数添加到 onClick 函数

<button onClick={this.fetchData} />

and map the data (this is in the render not in the button onClick).并映射数据(这是在渲染中而不是在 onClick 按钮中)。

items.map((key, index) => {
  return(
    <blockquote>
      <i key={item.name}>
      Name: </i> {item.name};
    </blockquote>
  )
})

It automatically adds it when the state changes, you want to add a loading display here to wait for the fetch to finish.当状态改变时它会自动添加它,你想在这里添加一个加载显示以等待获取完成。

export default class Ccomponent extends Component{
  constructor(props){
   super(props);
    this.state = {
    items: [], index: '', showResult: false
    };
  }
  handleClick() { 
   this.setState({showResult: true});
  }
  componentDidMount(){
    fetch("https://jsonplaceholder.typicode.com/users")
    .then(res => res.json())
    .then(
     (result) => {
    this.setState({
      items: result
    });
     }
   )



   }

  render(){
     const {items} = this.state;
     return(
      <div>
        <button key={index} onClick={this.handleclick.bind(this)}>klik</button>
        {showResults ? 
          items.map(item => (
           <blockquote>
            <i key={item.name}>
            Name: </i> {item.name};
           </blockquote>
          ))
          : null
        }
      </div>
     )
   }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM