javascript - 需要使用 fetch 从(laravel api)获取数据,然后将其解析到另一个函数

标签 javascript php reactjs laravel react-admin

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

关于javascript - 需要使用 fetch 从(laravel api)获取数据,然后将其解析到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68021236/

相关文章:

javascript - 如何在 Phaser 中获取 Sprite 的 activePointer 按下持续时间

php - 将 flex/php 连接到 Active Directory

javascript - 没有 React 的 Typescript 中的 JSX

javascript - WordPress php 下拉菜单点击即可

php - 我是否需要安装 ffmpeg-php 才能使用 ffmpeg?

reactjs - redux-form 多个复选框,单个数组中的值,没有 bool 值

reactjs - JSS 中的简单选择器和嵌套选择器

javascript - typescript如何实现枚举?

javascript - UIWebView - 调试 javascript

javascript - 如何仅传递 javascript 对象的内容,而不迭代每个值?