【问题标题】:Need to get data from (laravel api) using fetch then parse it on to another function需要使用 fetch 从(laravel api)获取数据,然后将其解析到另一个函数
【发布时间】:2021-09-02 08:51:51
【问题描述】:

我是 React 的初学者。我使用(Laravel API)在应用程序中获取数据并对其进行操作。 但数据仅在函数范围内可用。 如何在函数之外检索它并在其他地方使用它? 怎么可能?

//Function to get data from API
var userId = localStorage.getItem("userid")
const OrderStoryIds = fetch(`${"/api/v1/order?user_id=" + userId}`,{
        headers:{
            Authorization: "bearer " + localStorage.getItem("token")
    }}).then((response) => response.json()).then((order) => {
        var record={};
        if(order !== null) {
            order.forEach(function (items, index) {
                record[items.story_id]= items.status    
            });
        }
    return record
});
const printOrderStoryId = (id) => {
    OrderStoryIds.then((result) => {
        console.log(result[id]);
        var isAlreadyPurchased = result[id] === 1? true: false;
        console.log(isAlreadyPurchased);
        return isAlreadyPurchased;
});
};

const StoriesShow = (props, { key }) => {
        return (
            <div className="col-md-4" key={key}>
//This is where I want to call the above function and use the result for further use/something
            <div className="image-prinze">
                <img src={require('../../../../../public/images/frontend/' + props.image)} alt="" />
                {printOrderStoryId(props.id)? (
                   <div className="button-prinze">
                        <a href={'/storydetail/' + props.id} className="btn btn-prinze">Mehr erfahren</a>
                </div>): 
                (<div className="button-prinze">
                <span className="btn btn-prinze">already purchased</span>
        </div>)}
            </div>
        </div>
    );
}

【问题讨论】:

    标签: javascript php reactjs laravel react-admin


    【解决方案1】:

    fetch() 是异步的,因此您不能简单地返回函数范围之外的变量。但是,有一些解决方法:

    var myVar = null;
    
    fetch('http://example.com').then(function(data) {
        myVar = data.myVar
    });
    
    // your render should run when variables change
    render() {
        return (myVar ?? 'not fetched yet');
    }
    

    确保(如上所示)在初始渲染时myVar 的值是null,并且仅在后续调用中填充。所以你的render() 方法不能依赖myVar 有一个值。

    【讨论】:

      猜你喜欢
      • 2021-12-31
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 2019-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多