[英]Access fresh REDUX state in function of React component
I'm using React and React-Redux-Toolkit and difficulties accessing the updated state from within a function.我正在使用 React 和 React-Redux-Toolkit,但很难从 function 中访问更新后的 state。
I have a custom React Component which I pass a variable of my state:我有一个自定义 React 组件,我传递了一个 state 的变量:
const { useEffect, useState } = React; const ExternalComponent = ({ func }) => { func(); return ( <div></div> ); }; const Component = ({ state }) => { console.log("Component", state); const someFunction = () => { console.log("state", state); }; return ( <ExternalComponent func={someFunction} /> ); }; const Page = () => { const [state, setState] = useState(); useEffect(() => { setState(true); }, []); return ( <Component state={state} /> ); }; ReactDOM.render( <Page />, document.getElementById('root') );
<body> <div id="root"></div> <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script> <script src="https://unpkg.com/react@16/umd/react.production.min.js"></script> <script src="https://unpkg.com/react-dom@16/umd/react-dom.production.min.js"></script> <script type="text/babel" src="main.js"></script> </body>
On initial page render the component prints Component undefined
, because state
is yet undefined
, which is understandable and not the problem.在初始页面呈现组件打印Component undefined
,因为state
尚未undefined
,这是可以理解的,而不是问题所在。
When I update state
by any means, the component re-renders and prints Component <the change>
, which is also as expected.当我以任何方式更新state
时,组件重新呈现并打印Component <the change>
,这也是预期的。
However, someFunction()
will not update and still print the old state
, which is still undefined
.但是, someFunction()
不会更新并且仍然打印旧的state
,它仍然是undefined
。
How do I get someFunction()
to "update", ie print the updated state
?如何让someFunction()
进行“更新”,即打印更新后的state
?
Edit: Typo编辑:错别字
Edit2: I created a code snippet in which everything works as expected. Edit2:我创建了一个代码片段,其中一切都按预期工作。 However, in my actual code I'm using PaypalButtons , where I pass someFunction
to createOrder
.但是,在我的实际代码中,我使用的是PaypalButtons ,我将someFunction
传递给createOrder
。 I'm not sure how PaypalButtons works and why someFunction
would not get updated.我不确定 PaypalButtons 是如何工作的以及为什么someFunction
不会更新。
Edit3: I'm using paypal-react-js Edit3:我正在使用paypal-react-js
This is happening because you have a stale value.发生这种情况是因为您有过时的价值。 Try using useCallback
尝试使用useCallback
import { useCallback } from 'react';
const Component = ({ statefulVariable }) => {
console.log("Component", statefulVariable);
const someFunction = useCallback(() => {
console.log(statefulVariable);
}), [statefulVariable]);
return (
<SomeThirdPartyComponent callback={someFunction}/>
);
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.