我如何只取一次?

时间:2020-05-23 03:16:31

标签: javascript reactjs fetch-api restapi

我想从称为“ randomuserAPI”的其他API中获取名称和照片,以添加到我网站上的某种卡片上,但是它只是不断地一次又一次地获取,并且永远不会停下来(我只想要一个随机数和一张照片,但是它一直在不断更新这些内容。

这是我的Course元素,其中使用获取的数据创建卡,该数据是在其他地方的函数内部获取的。

import React, { useState } from 'react';
import '../App.css';
import {getUser} from '../library/getUsers.js'


const Course = ({author}) => { 

    const [userInfo, changeUserInfo] = useState('User')
    const [userPhoto, changeUserPhoto] = useState('https://i.stack.imgur.com/l60Hf.png')

    getUser(changeUserInfo, changeUserPhoto)

    return(
        <div className="course">
            <h4>{userInfo}</h4>
            <p>{author}</p>
            <img src={userPhoto} width="200px" height="200px" alt=""></img>
        </div>
    );
}

export default Course;

这是获取API的函数:

export async function getUser(changeUserInfo, changeUserPhoto){

    await fetch('https://randomuser.me/api?results=3')
    .then(res => res.json())
    .then((user) => {
        changeUserInfo(`${user.results[0].name.first} ${user.results[0].name.first}`)
        changeUserPhoto(user.results[0].picture.large)
    })
}

我不知道这里是否有什么问题,但这是App元素:

import React from 'react';
import Course from './elements/course';
import './App.css';

function App() {
  return (
    <div className="app">
      <Course 
        author = 'Tato Gucci'
      />  
    </div>
  );
}

export default App;

3 个答案:

答案 0 :(得分:1)

问题:

render -> getUser -> setting State -> re-render -> getUser .....
const Course = ({author}) => { 

    const [userInfo, changeUserInfo] = useState('User')
    const [userPhoto, changeUserPhoto] = useState('https://i.stack.imgur.com/l60Hf.png')

    //------------- ISSUE -------------
    // `getUser` get called when ever component get rendered
    // and it is setting up state , so it is causing re-rendering
    // so it's kind of infinte loop 
    // render -> getUser -> setState -> re-render .....
    getUser(changeUserInfo, changeUserPhoto)'

    return(
        <div className="course">
            <h4>{userInfo}</h4>
            <p>{author}</p>
            <img src={userPhoto} width="200px" height="200px" alt=""></img>
        </div>
    );
}

解决方案:

您可以将getUser放在useEffect内:这样,只有在组件挂载时它才会被调用

useEffect(() => {
    getUser(changeUserInfo, changeUserPhoto)
},[]);

答案 1 :(得分:0)

getUser不受任何限制将导致无限循环(组件Course渲染>调用getUser>更改userInfouserPhoto>触发渲染{{1 }}>再次致电Course> ...)

您必须将引起副作用(获取API)的函数放入getUser钩子中,在此上下文中为useEffect函数。

getUser(changeUserInfo, changeUserPhoto)

空数组确保useEffect = (() => { getUser(changeUserInfo, changeUserPhoto) }, []) 函数仅运行一次。

您应该阅读有关useEffect hook

的更多信息

答案 2 :(得分:0)

据我了解,您的担忧是:
您希望从API获得单个结果。 您需要结果是恒定的并且不能更改。

使用/usr/include/c++/7/bits/std_function.h:183: undefined reference to `__asan_report_store8' /usr/include/c++/7/bits/std_function.h:183: undefined reference to `__asan_report_load8' ../../../debug/liblqf.a(filter.cc.o): In function `std::_Function_base::_Base_manager<lqf::sboost::DictLess<parquet::PhysicalType<(parquet::Type::type)1> >::scanPage(unsigned long, unsigned char const*, unsigned long*, unsigned long)::{lambda(int)#1}>::_M_init_functor(std::_Any_data&, {lambda(int)#1}&&, std::integral_constant<bool, true>)': 代替使用https://randomuser.me/api?results=3 您正在获取3个结果,并期望得到一个结果。

要使结果恒定,您需要在获取之前将获取的结果存储在数据库中,并检查数据是否存在。您只需要获取数据库中不存在的数据即可。