Add : fetch shorten sentences from the server
I used axios for ajax.
Showing
2 changed files
with
48 additions
and
4 deletions
1 | import React, { Component } from 'react'; | 1 | import React, { Component } from 'react'; |
2 | import logo from './logo.png'; | 2 | import logo from './logo.png'; |
3 | import './App.css'; | 3 | import './App.css'; |
4 | +import axios from 'axios'; | ||
4 | 5 | ||
5 | class App extends Component { | 6 | class App extends Component { |
7 | + constructor(props){ | ||
8 | + super(props); | ||
9 | + this.state = { | ||
10 | + shorten : [] | ||
11 | + }; | ||
12 | + | ||
13 | + this.fetchShorten = this.fetchShorten.bind(this); | ||
14 | + this.printShorten = this.printShorten.bind(this); | ||
15 | + } | ||
16 | + | ||
17 | + componentDidMount(){ | ||
18 | + this.fetchShorten(); | ||
19 | + } | ||
20 | + | ||
21 | + fetchShorten() { | ||
22 | + var URL = 'http://localhost:4000'; | ||
23 | + return axios.get(URL) | ||
24 | + .then((response) => { | ||
25 | + console.log(response); | ||
26 | + this.setState({ | ||
27 | + shorten : response.data.shorten | ||
28 | + }); | ||
29 | + }) | ||
30 | + .catch((error) => { | ||
31 | + this.setState({ | ||
32 | + shorten : error | ||
33 | + }); | ||
34 | + }); | ||
35 | + } | ||
36 | + | ||
37 | + printShorten() { | ||
38 | + if(this.state.shorten){ | ||
39 | + return ( | ||
40 | + <div> | ||
41 | + <p>1 : {this.state.shorten[0]}</p> | ||
42 | + <p>2 : {this.state.shorten[1]}</p> | ||
43 | + <p>3 : {this.state.shorten[2]}</p> | ||
44 | + </div> | ||
45 | + ); | ||
46 | + } | ||
47 | + } | ||
48 | + | ||
6 | render() { | 49 | render() { |
7 | return ( | 50 | return ( |
8 | <div className="App"> | 51 | <div className="App"> |
9 | <div className="App-header"> | 52 | <div className="App-header"> |
10 | <img src={logo} className="App-logo" alt="logo"/> | 53 | <img src={logo} className="App-logo" alt="logo"/> |
11 | - <h2>Welcome to 3Line</h2> | 54 | + <h2>Redesigned by 3Line</h2> |
55 | + </div> | ||
56 | + <div className="App-intro"> | ||
57 | + {this.printShorten()} | ||
12 | </div> | 58 | </div> |
13 | - <p className="App-intro"> | ||
14 | - Calculating... | ||
15 | - </p> | ||
16 | </div> | 59 | </div> |
17 | ); | 60 | ); |
18 | } | 61 | } | ... | ... |
-
Please register or login to post a comment