如何更新反应状态变量以用于其他功能

时间:2019-11-13 18:08:37

标签: reactjs react-native react-hooks

我想立即看到菜谱状态变量充满了来自API get请求的数据。 likedByUser函数未及时更新。如果我将Cookbook作为依赖项添加到useEffect()依赖项数组中,则它将进入无限渲染循环。在我进入likedByUser函数时,有什么方法可以查看更新的食谱数组吗?

const RecipeList = (props) => {
    const [recipes, setRecipes] = useState([]);
    const [cookbook, setCookbook] = useState([]);
    const cookbookURL = 'https://url';

    const getCookbook = async () => {
        const axiosAuth = await axiosWithAuth();
        const res = await axiosAuth.get(cookbookURL);  //resolves successfully
        setCookbook(res.data);
    }

    const likedByUser = () => {
        console.log('cookbook',cookbook);  //cookbook comes back as an empty array
    }

    useEffect(() =>{
        getCookbook();
        likedByUser();  //I want to access the cookbook state variable here
        setRecipes(props.recipes);
    },[]);

    return <View>{cookbook.map(recp => <Recipe recipe={recp} />)}</View>

0 个答案:

没有答案