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

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

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

const search = async () => {
    fetch(`${api.base}weather?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 .

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

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

  useEffect(() => {
    fetch(`${api.base}weather?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)} 是多余的

更多资源:

【讨论】:

    【解决方案2】:
    useEffect( () => search(), [])  
    

    【讨论】:

    • 我想我的答案中的方法更惯用,因为它会在查询更改时自动重新执行搜索。它还消除了命令式onKeyPress={search} 事件处理程序
    • 您可以使用 useEffect 并将搜索查询传递给依赖项表,因此每次变量更改时都会使用新结果进行 re_render。
    猜你喜欢
    • 2022-01-01
    • 2020-10-18
    • 2018-04-04
    • 2019-12-21
    • 2019-08-29
    • 2017-12-26
    • 2020-01-14
    • 1970-01-01
    • 2017-02-09
    相关资源
    最近更新 更多