1 回答
TA贡献1820条经验 获得超9个赞
您需要通过React 的 useCallbackincreaseCounter()
包装到回调中。实际上,因此重新渲染,重置.api.registerCallback()
counter
您可以在此处了解有关此行为的更多信息。
import React, { useState, useCallback, useEffect } from "react";
import ReactDOM from "react-dom";
class ThirdPartyApi {
registerCallback(callback) {
this.callback = callback;
}
triggerCallback() {
this.callback();
}
}
let api = new ThirdPartyApi();
function App() {
const [counter, setCounter] = useState(5);
const increaseCounter = useCallback(() => {
setCounter(counter + 1);
console.log(counter);
}, [counter]);
useEffect(() => {
api.registerCallback(increaseCounter);
}, [increaseCounter]);
return (
<div className="App">
<p>
<button onClick={() => increaseCounter()}>Internal increase</button>
</p>
<p>
<button onClick={() => api.triggerCallback()}>External increase</button>
</p>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
添加回答
举报