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



我正试图通过fetch函数从服务器获取数据。但我需要这些数据显示在这些按钮之后。如果没有该按钮,则显示数据。这是我的代码:

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>
)
}
}

从componentDidMount转移该函数,然后将fetch函数添加到onClick函数中

<button onClick={this.fetchData} />

并映射数据(这是在渲染中,而不是在按钮onClick中(。

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

当状态发生变化时,它会自动添加它,您需要在此处添加一个加载显示以等待提取完成。

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>
)
}
}

最新更新