需要使用 fetch 从laravel api获取数据,然后将其解析为另一个函数

问题描述

我是 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>
    );
}

解决方法

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 具有值。