如何使用React useState多次渲染

时间:2020-11-09 14:06:04

标签: javascript reactjs components

我试图在React中定义一个函数,必须多次渲染该组件,因为我要在函数本身内部多次更改状态。我知道useState挂钩会在函数末尾重新渲染组件,因此,在设置新状态后如何立即重新渲染组件?代码是这样的:

function App() {
  const [state, setState] = useState(0);

  const getServerState = () => {
    e.preventDefault();
    // Send something to the server and put the response on "response"
    if (response.customVar === "uploading") {
      setState(1);
      // Send another request to the server and wait for the response
      if (newResponse.customVar === "uploaded" && state === 1) {
        setState(2);
      } else {
        throw new Error("Error in uploading response");
      }
    } else {
      throw new Error("Error in response");
    }
  };

  const checkState() => {
    if (state === 0) return "Waiting for user click";
    else if (state === 1) return "Your file is being uploaded";
    else if (state === 2) return "Your file is ready!";
  };

  return (
    <div>
    {checkState()}
    <button onClick={getServerState}>
      Click me
    </button>
  </div>)
}

在上面的示例中,我没有得到任何重新渲染,因为状态更改为1“为时已晚”,而检查状态为1的 if 没有通过。有针对这个的解决方法吗?我不能使用useEffect钩子,因为效果将更新状态,这将导致循环。

1 个答案:

答案 0 :(得分:0)

您不能在setState之后立即获取状态,相反,您需要定义一个临时布尔变量。

function App() {
  const [state, setState] = useState(0);

  const getServerState = () => {
    e.preventDefault();
    var isUploaded = false;
    // Send something to the server and put the response on "response"
    if (response.customVar === "uploading") {
      setState(1);
      isUploaded = true;
      // Send another request to the server and wait for the response
      if (newResponse.customVar === "uploaded" && isUploaded) {
        setState(2);
      } else {
        throw new Error("Error in uploading response");
      }
    } else {
      throw new Error("Error in response");
    }
  };

  const checkState() => {
    if (state === 0) return "Waiting for user click";
    else if (state === 1) return "Your file is being uploaded";
    else if (state === 2) return "Your file is ready!";
  };

  return (
    <div>
    {checkState()}
    <button onClick={getServerState}>
      Click me
    </button>
  </div>)
}