简体   繁体   English

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

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

I have read about React hooks and wanted to try it on this new website I have been developing. 我已阅读有关React钩子的信息,并希望在我开发的这个新网站上试用它。 I am trying to pass an async function as a prop. 我试图传递异步函数作为道具。 Part of the function is to set my "cities" state and console log just to see if the API works. 该函数的一部分是设置我的“城市”状态和控制台日志,以查看API是否有效。 I have been receiving "setCities is not a function" error or, cities returns undefined if I just console log it directly. 我一直在接收“setCities不是函数”错误,或者如果我只是直接控制台登录,则返回undefined。 I think the function can't access the {cities, setCities} state. 我认为该函数无法访问{cities, setCities}状态。 I have tried it in class component and it works. 我已经在类组件中尝试了它并且它可以工作。 Has anyone encountered similar situations? 有没有人遇到类似的情况? Below is the code sample: 以下是代码示例:

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 an array, not an object... useStates返回一个数组,而不是一个对象......

So you can change 所以你可以改变

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

to

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

And it should work. 它应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM