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的回调。问题是当我尝试向其推送新消息时,输出数组始终为空。
答案 0 :(得分:1)
通过更新状态时使用回调方法解决:
const handleOutput = (message) => {
setOutput(previousOutput => [...previousOutput, message]);
}