如何在 React 中自动发出 API 请求?

Posted

技术标签:

【中文标题】如何在 React 中自动发出 API 请求?【英文标题】:How to make an API request automatically in React? 【发布时间】:2021-04-02 02:28:36 【问题描述】:

我正在尝试为我的浏览器创建自定义主页。我已经实现了一个 API 来显示天气,但只有在我按 Enter 时才有效。我想在加载页面时自动显示数据,无需按 Enter,自动显示布里斯托尔天气,当我键入另一个位置时,api 将能够请求和呈现。我尝试了很多方法,例如(移除钩子,更改钩子的初始状态但似乎没有任何效果)这是我的代码:

    const [query, setQuery] = useState('Bristol');
    const [weather, setWeather] = useState();

const search = async () => 
    fetch(`$api.baseweather?q=$query&units=metric&APPID=$api.key`)
    .then(res => res.json())
    .then(result => 
        setWeather(result);
        setQuery('')
        console.log(result)
    );

    return(
        <div className="app">
            <main>
                <div className="search-box">
                    <input
                        type="text"
                        className="search-bar"
                        placeholder="Search..."
                        onChange=e => setQuery(e.target.value)
                        value=query
                        onKeyPress=search
                    />
                </div>
                (typeof weather.main != "undefined") ? (
                    <div>
                    <div className="location-box">
                        <div className="location">weather.name</div>
                        <div className="date">dateBuilder(new Date())</div>
                    </div>
                        <div className="weather-box">
                            <div className="temp">
                                Math.round(weather.main.temp)
                            </div>
                            <div className="weather">
                                weather.weather[0].main
                            </div>
                        </div>
                    </div>
                ) : ('')
            </main>
        </div>
    )
 

我是 ReactJS 的新手,这有点令人困惑,因为在这里我使用相同的文件进行编码和渲染,我之前这样做过,但我使用的是带有 express 等的纯 javascript。我渲染成 html .

【问题讨论】:

你可能需要修改 ReactJS hooks reactjs.org/docs/hooks-overview.html. 这能回答你的问题吗? How to call loading function with React useEffect only once @NishargShah 快到了,它会加载,但不到 1 秒就会自动清除。 【参考方案1】:

尝试将fetch 调用封装在useEffect 中:

  useEffect(() => 
    fetch(`$api.baseweather?q=$query&units=metric&APPID=$api.key`)
      .then((res) => res.json())
      .then((result) => 
        setWeather(result);
        console.log(result);
      );
  , [query]);

第二个参数是一个所谓的依赖数组。每当其内容更改时,效果都会重新运行,请参阅https://reactjs.org/docs/hooks-effect.html。

同时删除onKeyPress=search,因为它与onChange=e =&gt; setQuery(e.target.value) 是多余的

更多资源:

Robin Wieruch:如何使用 React Hooks 获取数据? https://www.robinwieruch.de/react-hooks-fetch-data

【讨论】:

【参考方案2】:
useEffect( () => search(), [])  

【讨论】:

我想我的答案中的方法更惯用,因为它会在查询更改时自动重新执行搜索。它还消除了命令式onKeyPress=search 事件处理程序 您可以使用 useEffect 并将搜索查询传递给依赖项表,因此每次变量更改时都会使用新结果进行 re_render。

以上是关于如何在 React 中自动发出 API 请求?的主要内容,如果未能解决你的问题,请参考以下文章