简体   繁体   English

即使已更改了 state,但视图尚未在 React / Next.js 中再次呈现

[英]Even if a state has been changed, but the view has not been rendered again in React / Next.js

Even if a state has been changed, but the view has not been rendered again in React / Next.js.即使 state 已更改,但视图尚未在 React / Next.js 中再次呈现。 Here is my code and console.log result.这是我的代码和 console.log 结果。

As a prerequisite, I think I understand the behavior of useState, useEffect, Promise, and async/await, but I couldn't figure it out any more on my own.作为先决条件,我想我了解 useState、useEffect、Promise 和 async/await 的行为,但我自己无法弄清楚。

The return value of GetGithubData is Promise, so I'm wondering if that's the reason why the update doesn't run simply because I can't access the object inside. GetGithubData 的返回值是 Promise,所以我想知道这是不是因为我无法访问里面的 object 而导致更新无法运行的原因。 However, if that is the case, in order to resolve Promise, I have to add "await", and in order to do so, I have to change to the function to "async" function, and when I change it to the async function, I get an error if the "return" returns an object, and the radar chart is not displayed in the first place.但是,如果是这种情况,为了解决 Promise,我必须添加“await”,为此,我必须将 function 更改为“async” ZC1C425268E68785D1AB5074 时function,如果“return”返回一个object,我会得到一个错误,并且首先没有显示雷达图。

Can someone please tell me how to fix this?有人可以告诉我如何解决这个问题吗? I've seen a few similar questions, but none of them seemed to fit.我见过一些类似的问题,但似乎没有一个适合。

Radarchart.tsx code is below, which is a component drawing a radarchart graph like this. Radarchart.tsx 代码如下,它是一个像这样绘制雷达图的组件。 And this graph itself is successfully drawn in my browser but the number of commit to Github is still 20 instead of 12, which means the result of useEffect is not rendered again.这个图本身在我的浏览器中绘制成功,但是提交到 Github 的次数仍然是 20 而不是 12,这意味着 useEffect 的结果不会再次呈现。

雷达图

import React, { useEffect, useState } from "react";
import {
  Chart,
  LineElement,
  PointElement,
  RadialLinearScale,
} from "chart.js";
import { Radar } from "react-chartjs-2";
import GetGithubData from "../services/githubService";

const RadarChart = () => {
  const [githubData, setGithubData] = useState({});

  useEffect(() => {
    setGithubData(GetGithubData());
  }, []);

  const randomNumber1 = githubData["total"] ? githubData["total"] : 20;
  console.log(githubData);
  console.log(randomNumber1);
  const randomNumber2 = 35;
  const randomNumber3 = 45;
  const randomNumber4 = 75;
  const randomNumber5 = 85;

  const data = {
    datasets: [
      {
        data: [
          randomNumber1,
          randomNumber2,
          randomNumber3,
          randomNumber4,
          randomNumber5,
        ],
        backgroundColor: "rgba(255, 99, 132, 0.2)",
        borderColor: "rgba(255, 99, 132, 1)",
      },
    ],
  };

  Chart.register(
    LineElement,
    PointElement,
    RadialLinearScale,
  );

  return <Radar data={data} options={options} />;
};

export default RadarChart;

githubService.tsx is a service file to fetch data that I want to fetch from Github API. githubService.tsx 是一个服务文件,用于获取我想从 Github API 获取的数据。

const GetGithubData = async () => {
  const owner = "aaaa";
  const repo = "bbbb";
  const url = `https://api.github.com/repos/${owner}/${repo}/stats/contributors`;

  const response = await fetch(url);
  const data = await response.json();
  return data[0];
};

export default GetGithubData;

The result of console.log are below. console.log 的结果如下。

在此处输入图像描述

GetGithubData is an async function, meaning it implicitly returns a Promise. GetGithubData是一个async function,这意味着它隐式返回 Promise。 You are saving the Promise object into the githubData state.您将 Promise object 保存到githubData state 中。

useEffect(() => {
  setGithubData(GetGithubData());
}, []);

You are correct that you need to await it resolving.你是对的,你需要等待它解决。

You can chain from the returned promise and call setGithubData in the .then block with the returned value:您可以从返回的 promise 链接并使用返回值在.then块中调用setGithubData

useEffect(() => {
  GetGithubData()
    .then(data => {
      setGithubData(data);
    });
}, []);

Or create an async function in the useEffect hook and await the value.或者在useEffect挂钩中创建一个async function 并await该值。

useEffect(() => {
  const getGitHubData = async () => {
    const data = await GetGithubData();
    setGithubData(data);
  };

  getGitHubData();
}, []);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM