猿问

第三方 API 需要访问 React 应用程序中的状态

我们有一个 React 应用程序,它与第三方库通信以进行电话集成。每当有人打电话时,第三方库就会触发 React 应用程序内部的回调函数。到现在为止一切都很好,但是现在这个回调函数需要访问当前状态,这似乎会带来问题。这个回调函数内部的状态,似乎总是处于初始值并且永远不会更新。


我在这里做了一个小沙盒来描述这个问题:https ://codesandbox.io/s/vigorous-panini-0kge6?file=/src/App.js


在沙盒中,当我单击“内部增加”时,计数器值会正确更新。但是,相同的函数已添加为 ThirdPartyApi 的回调,当我单击“外部增加”时将调用它。当我这样做时,计数器值恢复为 useState 中的默认值。


我怎样才能让第三个库知道来自 React 内部的状态更新?


应用程序.js:


import React, { useState, useEffect } from "react";

import ThirdPartyApi from "./third-party-api";

import "./styles.css";


let api = new ThirdPartyApi();


export default function App() {

  const [counter, setCounter] = useState(5);


  const increaseCounter = () => {

    setCounter(counter + 1);

    console.log(counter);

  };


  useEffect(() => {

    api.registerCallback(increaseCounter);

  }, []);


  return (

    <div className="App">

      <p>

        <button onClick={() => increaseCounter()}>Internal increase</button>

      </p>


      <p>

        <button onClick={() => api.triggerCallback()}>External increase</button>

      </p>

    </div>

  );

}

第三方-api.js:


export default class ThirdPartyApi {

  registerCallback(callback) {

    this.callback = callback;

  }


  triggerCallback() {

    this.callback();

  }

}


慕森王
浏览 127回答 1
1回答

慕妹3146593

您需要通过React 的 useCallbackincreaseCounter()包装到回调中。实际上,因此重新渲染,重置.api.registerCallback()counter您可以在此处了解有关此行为的更多信息。import React, { useState, useCallback, useEffect } from "react";import ReactDOM from "react-dom";class ThirdPartyApi {&nbsp; registerCallback(callback) {&nbsp; &nbsp; this.callback = callback;&nbsp; }&nbsp; triggerCallback() {&nbsp; &nbsp; this.callback();&nbsp; }}let api = new ThirdPartyApi();function App() {&nbsp; const [counter, setCounter] = useState(5);&nbsp; const increaseCounter = useCallback(() => {&nbsp; &nbsp; setCounter(counter + 1);&nbsp; &nbsp; console.log(counter);&nbsp; }, [counter]);&nbsp; useEffect(() => {&nbsp; &nbsp; api.registerCallback(increaseCounter);&nbsp; }, [increaseCounter]);&nbsp; return (&nbsp; &nbsp; <div className="App">&nbsp; &nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={() => increaseCounter()}>Internal increase</button>&nbsp; &nbsp; &nbsp; </p>&nbsp; &nbsp; &nbsp; <p>&nbsp; &nbsp; &nbsp; &nbsp; <button onClick={() => api.triggerCallback()}>External increase</button>&nbsp; &nbsp; &nbsp; </p>&nbsp; &nbsp; </div>&nbsp; );}const rootElement = document.getElementById("root");ReactDOM.render(&nbsp; <React.StrictMode>&nbsp; &nbsp; <App />&nbsp; </React.StrictMode>,&nbsp; rootElement);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答