Where is the right place to call the httpRequest of an API in React?
在使用React的时候我应该在哪里调用API有点困惑,我一直把调用放在componentDidMount上并在那里进行setState,就像这样:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | constructor(props) { super(props); this.state = {info: []}; } componentDidMount() { this.ObtenerVariables(this.props.enlace1, this.props.enlace2); } ObtenerVariables(consulta1, consulta2){ var httpRequest = new XMLHttpRequest(); httpRequest.open('GET', consulta1,false); httpRequest.send(); var cons1 =JSON.parse(httpRequest.response); var cantArticulos = cons1.data[0].cantidad_articulos; httpRequest.open('GET', consulta2,false); httpRequest.send(); var cons2 =JSON.parse(httpRequest.response); var cantAutores = cons2.data[0].cant_autores; this.setState({ info: [cantArticulos, cantAutores] }) } |
,然后像这样访问信息
但是我在网上看到一些人说这不好,因为它会给您带来性能问题,这与我想要的完全相反,我需要网站加载得更快。
这是不好的做法吗?是否会影响网站的性能?有什么更好的方法可以做到这一点?考虑到该网站需要发出大约16个API请求。
Api呼叫的最佳位置是
请检查以下两个示例:
类组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | import React from"react"; import axios from 'axios'; export default class PostListPage extends React.Component { state = { posts: [] }; componentDidMount() { axios.get(`https://jsonplaceholder.typicode.com/posts`) .then(res => { const posts = res.data; console.log(posts); this.setState({posts:posts}); }) } render() { return ( <React.Fragment> <ul> { this.state.posts? this.state.posts.map(post => <li key={post.id}>{post.title} </li> ) : null } </ul> </React.Fragment> ); } } |
功能组件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | import React, {useEffect, useState} from"react"; import axios from 'axios'; export default function PostListPage() { const [posts, setPost] = useState([]); let signal = axios.CancelToken.source(); useEffect(() => { let isSubscribed = true; axios.get('https://jsonplaceholder.typicode.com/posts', { cancelToken: signal.token, }) .then(res => { const posts = res.data; setPost(posts); }).catch(err => { console.log(err); }); return function cleanup() { isSubscribed = false; signal.cancel('Api is being canceled'); } }, []); return ( <React.Fragment> <ul> { posts? posts.map(post => <li key={post.id}>{post.title} </li> ) : null } </ul> </React.Fragment> ); } |