0

我在使用react-image-mapper库时遇到问题。我想在单击图像中的区域时设置变量的状态,并立即使用正文中的新变量状态触发 API 调用。但是,单击图像后,旧状态会放入正文中,而不是新设置的状态。这是一个例子:

这是 JSX——它会提示一个clicked函数,然后触发 API ( updateMatchState):

          <ImageMapper
            onClick={(area, _, e) => {
              clicked(area, e);
              updateMatchState();
            }}
          ></ImageMapper>

clicked功能:

 const clicked = (area, e) => {
    const width = 700;
    const coordinates = { x: e.nativeEvent.layerX };
    let pitchYards = Math.round(
      (((coordinates.x / width) * 97.5 - 10.5) / 77) * 100
    );

    modelPosession === 0
      ? setEndYfog(pitchYards <= 0 ? 0 : pitchYards >= 100 ? 100 : pitchYards)
      : setEndYfog(
          pitchYards <= 0 ? 100 : pitchYards >= 100 ? 0 : 100 - pitchYards
        );

  };

最后updateMatchState

const [endYfog, setEndYfog] = useState(0);
const [modelPosession, setModelPosession] = useState(0);

const matchStateData = () => {

    console.log("endYfog value is: " + endYfog); //This prints 0 the first time, and upon state update it prints new value
    const matchStateUpdate = {};
    const playResult = {};
    playResult["yfog"] = endYfog;
    return matchStateUpdate;
}

 const updateMatchState = () => {

    model
      .post("/update", matchStateData())
      .then((response) => {
        const pitchState = response.data.pitchState;
        setPitchState(pitchState);
      })
      .catch((err) => {
        console.log(`POST match state update failed: ${err}`);
      });
  };

目前, 的值endYfog作为 0 进入updateMatchState函数体。我希望 的值setEndYfog成为该函数的值。我希望这是有道理的——我该怎么做?

4

0 回答 0