【问题标题】:React - trying to save fetched data in a variable but the variable returns emptyReact - 尝试将获取的数据保存在变量中,但变量返回空
【发布时间】:2021-05-20 20:46:55
【问题描述】:

我使用 async await 获取了 json 数据,我想将获取的数据保存在一个变量中,以便能够将它与我的组件中的地图一起使用, 数据正确地进入函数内部 - 我检查了警报,并且在函数内部的变量中它确实显示了所有数据,但是函数外部的变量以某种方式返回空。 这是一些代码: 以下代码中的两个警报都返回正确的数据。

export let fetchPosts = [];
export async function FetchPosts() {
    await axios.get('https://jsonplaceholder.typicode.com/posts').then(
        res => {
            alert(JSON.stringify(res.data))
            fetchPosts = JSON.stringify(res.data);
            alert(fetchPosts)
        }
    ).catch(err => {
        alert('err');
    })
}

import { fetchPosts } from '../services/post';
import { FetchPosts } from '../services/post';

export default function Posts() {
    function clickme() {
        FetchPosts()
    }
    return (<>
        <button onClick={clickme}>Click me</button>
        {fetchPosts.map((post, index) => (
            <div key={post.id} className="card" style={{ 'width': '16rem', 'display': 'inline-block', 'margin': '5px' }}>
                <div className="card-body">
                    <h6 className="title">{post.title}</h6>
                    <p className="card-text">{post.body}</p>
                </div>
            </div>
        ))}
    </>)
}

【问题讨论】:

  • React 在您获取数据之前进行渲染,然后在数据更改时没有告诉它重新渲染。您需要使用状态和效果挂钩的更全面的解决方案。

标签: node.js json reactjs axios


【解决方案1】:

状态是问题

React 不会在你的单例 fetchPosts 上自动重新加载。 相反,尝试...

export function FetchPosts() {
    return axios.get('https://jsonplaceholder.typicode.com/posts');
}

然后

import { useState } from 'react';
import { FetchPosts } from '../services/post';

export default function Posts() {
    const [posts, setPosts] = useState([]);
    function clickme() {
        FetchPosts().then(res => {
          setPosts(res.data);
        });
    }
    return (<>
        <button onClick={clickme}>Click me</button>
        {posts.map((post, index) => (
            <div key={post.id} className="card" style={{ width: '16rem', display: 'inline-block', margin: '5px' }}>
                <div className="card-body">
                    <h6 className="title">{post.title}</h6>
                    <p className="card-text">{post.body}</p>
                </div>
            </div>
        ))}
    </>)
}

https://codesandbox.io/s/jolly-almeida-q4331?fontsize=14&hidenavigation=1&theme=dark

如果您想要全局状态,那是您应该完全深入研究的另一个主题,但您可以使用单例来完成,您只需将它与钩子和事件发射器结合起来。我在这里https://codesandbox.io/s/react-typescript-playground-forked-h8rpu 有一个黑客版本,但你可能应该坚持使用 redux 或 mobx 或 AppContext,这更流行的模式。

【讨论】:

  • FetchPost 上的async 关键字在这里有什么不同吗?
  • 我试过这样做,但它通过我一个错误:TypeError: services_post__WEBPACK_IMPORTED_MODULE_1_.FetchPosts.then is not a function
  • @HåkenLid 你是对的。我不小心留下了这个。我的错。
  • 如果我理解正确你的问题 - 在我的 .then res 中我得到数据并正确显示在警报中
  • @Mindy haha​​ 找到并更正了。我在没有函数的情况下调用它。更新。 q4331.csb.app
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-24
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多