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

我正在尝试为我的浏览器创建自定义主页。我已经实现了一个 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。


婷婷同学_
浏览 45回答 2
2回答

噜噜哒

useEffect(&nbsp;()&nbsp;=>&nbsp;search(),&nbsp;[])

达令说

尝试将调用fetch包装在useEffect:&nbsp; useEffect(() => {&nbsp; &nbsp; fetch(`${api.base}weather?q=${query}&units=metric&APPID=${api.key}`)&nbsp; &nbsp; &nbsp; .then((res) => res.json())&nbsp; &nbsp; &nbsp; .then((result) => {&nbsp; &nbsp; &nbsp; &nbsp; setWeather(result);&nbsp; &nbsp; &nbsp; &nbsp; console.log(result);&nbsp; &nbsp; &nbsp; });&nbsp; }, [query]);第二个参数是所谓的依赖数组。每当其内容发生更改时,效果都会重新运行,请参阅https://reactjs.org/docs/hooks-effect.html。也删除,onKeyPress={search}因为它是多余的onChange={e => setQuery(e.target.value)}更多资源:Robin Wieruch:如何使用 React Hooks 获取数据?https://www.robinwieruch.de/react-hooks-fetch-data
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript