React Hooks - 作为 prop 传递的函数组件内的函数无法访问状态

React Hooks - function inside function component passed as prop can't access state

我已经阅读了有关 React hooks 的内容,并想在我一直在开发的这个新网站上尝试一下。我正在尝试将异步函数作为道具传递。部分功能是设置我的 "cities" 状态和控制台日志,只是为了查看 API 是否有效。我一直收到 "setCities is not a function" 错误或者城市 returns undefined 如果我只是控制台直接记录它。我认为该函数无法访问 {cities, setCities} 状态。我已经在 class 组件中尝试过它并且它有效。有没有人遇到过类似的情况?下面是代码示例:

import React, { useState } from "react";
import axios from "axios";
import Menu from "./Menu";

function App() {
    const { cities, setCities } = useState([]);

    const searchSubmit = async term => {
        try {
            const res = await axios.get("http://localhost:8080/general/search", {
                params: { city: term }
            });
            setCities(res.data);
            console.log(cities);
        } catch (err) {
            console.log(err.message);
        }
    };

    return (
        <div className="ui container">
            <Menu handleSearchSubmit={searchSubmit} />
        </div>
    );
}

useStates return 数组,不是对象...

所以你可以改变

const { cities, setCities } = useState([]);

const [ cities, setCities ] = useState([]);

它应该可以工作。