简体   繁体   English

尽管在 React Highcharts 点击事件中进行了更新,但仍显示旧的 state

[英]Old state is being shown despite updating in React Highcharts click event

I want the new state to show, but I get different behavior.我希望显示新的 state,但我得到了不同的行为。 I have three points (look at code below or sketch) and if I click a point, then whatever state value is at that time, in future clicks the old value is shown.我有三个点(查看下面的代码或草图),如果我单击一个点,那么无论 state 值当时是什么,将来单击都会显示旧值。 I am not sure what this is being caused by.我不确定这是由什么引起的。

For example: Click point A, then 0 is printed.例如:单击点 A,则打印 0。 Increment state, then click A, still 0 is printed.递增state,然后点A,还是打印0。 Click point B, 1 is printed.单击点 B,打印 1。 Click point A, still 0 is printed.点击A点,仍然打印0。

Sketch: https://stackblitz.com/edit/react-bwskb9?file=index.js草图: https://stackblitz.com/edit/react-bwskb9?file=index.js

import React, { useState, useEffect } from "react";
import { render } from "react-dom";
import HighchartsReact from "highcharts-react-official";
import Highcharts from "highcharts";

const LineChart = () => {
  const [hoverData, setHoverData] = useState(null);
  const [someState, setSomeState] = useState(0);
  const [chartOptions, setChartOptions] = useState({
    xAxis: {
      categories: ["A", "B", "C"]
    },
    series: [{ data: [1, 2, 3] }],
    plotOptions: {
      series: {
        point: {
          events: {
            click(e) {
              console.log(someState);
              setHoverData(e.point.category);
            }
          }
        }
      }
    }
  });

  const updateSeries = () => {
    setChartOptions({
      plotOptions: {
        series: {
          point: {
            events: {
              click(e) {
                console.log(someState);
                setHoverData(e.point.category);
              }
            }
          }
        }
      }
    });
  };

  useEffect(() => {
    updateSeries();
  }, [someState]);

  return (
    <div>
      <HighchartsReact highcharts={Highcharts} options={chartOptions} />
      <h3>Clicked over {hoverData}</h3>
      <button onClick={() => setSomeState(val => val + 1)}>Incr</button>
      <p>{someState}</p>
    </div>
  );
};

render(<LineChart />, document.getElementById("root"));

Apparently, this is not something that is a problem in HighchartJS, but React hooks in particular.显然,这不是 HighchartJS 中的问题,尤其是 React 钩子。 I solved this by using refs.我通过使用 refs 解决了这个问题。

Refer here: How To Solve The React Hook Closure Issue?参考这里: 如何解决 React Hook 关闭问题?

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

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