尝试更新时,状态始终是初始值

时间:2019-06-22 14:34:11

标签: reactjs

export const ExecutionProvider = (props) => {
    const [output, setOutput] = useState([]);

    const handleOutput = (message) => {
        const newOutput = [...output];

        newOutput.push(message);

        setOutput(newOutput);
    }

    const runCode = () => {
        const parsedCode = parseCode(code);

        const codeBlob = new Blob([parsedCode], { type: 'application/javascript' });
        const worker = new Worker(URL.createObjectURL(codeBlob));

        worker.onmessage = handleOutput;
    }

handleOutput函数用作运行某些代码的Webworker的回调。问题是当我尝试向其推送新消息时,输出数组始终为空。

1 个答案:

答案 0 :(得分:1)

通过更新状态时使用回调方法解决:

  const handleOutput = (message) => {
      setOutput(previousOutput => [...previousOutput, message]);
  }