I am trying to fetch data from the server via the fetch function. 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
<button onClick={this.fetchData} />
and map the data (this is in the render not in the button 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>
)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.