React JS:在 API 调用成功后获取上下文数据 [英] React JS: Get Context Data After getting success on API Call

查看:34
本文介绍了React JS:在 API 调用成功后获取上下文数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在获取上下文数据.

I am stuck at getting context data.

我有一个上下文和一个使用其数据的组件.

I have a context and a component which uses its data.

我需要在我的组件中获取有关 API 调用成功的上下文变量的更新数据.

I need to get the updated data of context's variable on API call success in my component.

那我该怎么做?这是我尝试过的.

so How can I do that ? Here what I have tried.

context.js

import React, { useState, createContext,useEffect } from 'react';
import {getData} from './actionMethods';

const NewContext = createContext();

function newContextProvider(props) {

 const [dataValue, setData] = useState([])

    useEffect(() => {
        const fetchMyData = async () => {
            const dataValue  = await getData(); // this is an API call

            setData(dataValue)
        };

        fetchMyData();
    }, []);

     
     return (
        <NewContext.Provider
            value={{
                state: {
                    dataValue
                },
                actions: {
                    
                }
            }}
        >
            {props.children}
        </NewContext.Provider>
    );
}


const newContextConsumer = newContext.Consumer;

export { newContextProvider, newContextConsumer, newGridContext };

myComponent.js

myComponent.js

import React, { useState, useContext } from 'react'

import context from './context'


import deleteAPI from './actionMethods'

function myComponent(props) {

const id= 10

const {state,actions} = useContext(context)
  
  deleteAPI(id).then(res => {
    if (res){
      // what should I write here to get the updated Data from the context which will call an API to get the updated data.    
    }
  })
  
  
}

任何帮助都会很棒.

谢谢.

推荐答案

作为一个通用示例,一种选择是在前端加载应用程序时从服务器获取数据.从那里您可以发送修改服务器数据的请求,同时更新您的本地版本.类似的东西:

As a generic example, one option is to fetch the data from the server when the app loads in the front-end. From there you can send requests to modify the server data and at the same time update your local version. Something like:

  1. 获取数据并保存到本地存储:[{id: 0, name: 'first'},{id: 1, name: 'second'}]
  2. 修改数据发送请求到服务器.例如删除一个项目.id: 0
  3. 一旦服务器响应确认操作成功,您就可以修改本地存储中的数据.[{id: 1, name: 'second'}]

您可以使用 Redux 存储或 React Context 处理数据.例如,使用上下文:

You can handle the data using a Redux store or a React Context. For example, using a Context:

export const ItemsContext = createContext([]);

export const ItemsContextProvider = props => {
    const [items, setItems] = useState([]);

    const deleteItem = id => {
        deleteItemsAxios(id).then(() => {
            setItems(items => items.filter(item => item.id !== id));
        });
    };

    useEffect(() => {
        const fetchItems = async () => {
            const items_fetched = await fetchItemsAxios();

            if (items_fetched) {
                setItems(items_fetched);
            } else {
                // Something went wrong
            }
        };

        fetchItems();
    }, []);

    return (
        <ItemsContext.Provider
            value={{
                items,
                deleteItem
            }}
        >
            {props.children}
        </ItemsContext.Provider>
    );
};

我们定义了一个组件来管理数据获取.数据项在一个状态内.当组件挂载时,我们获取项目并将它们保存在状态中.如果我们想删除一个项目,我们首先调用相应的 fetch 函数.一旦完成,如果成功,我们更新状态并删除该项目.我们使用 React Context 将 items 数据以及 deleteItem 函数传递给任何需要它们的组件.

We define a Component that will manage the data fetch. The data items are inside a state. When the Component mounts we fetch the items and save them in the state. If we want to delete an item we first call the corresponding fetch function. Once it finishes, if it was successful, we update the state and remove that item. We use React Context to pass the items data, as well as the deleteItem function, to any component that needs them.

如果您需要更多解释,请告诉我.

Let me know if you need more explanation.

这篇关于React JS:在 API 调用成功后获取上下文数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆