简体   繁体   English

更新后如何将 function 传递给 SetState 回调? (反应)

[英]How to pass a function to SetState callback after updating? (Reactjs)

I searched a lot before asking but can't seem to find a solution that works with me.在询问之前我进行了很多搜索,但似乎找不到适合我的解决方案。

I have a function that I need to be called after the state is set to the new value.我有一个 function,我需要在 state 设置为新值后调用它。

const onClickCallback = () => {
    setState(..., setCallback())
}

const setCallback = () => {
    console.log(State) // this prints the old State value
    if(State === something){
        ....
    }
}

Eventhough the function is being called as the setState callback, it still gets the older value.尽管 function 作为 setState 回调被调用,它仍然获得旧值。

I'm not sure if the problem is from my end or it's just not possible..我不确定问题是出在我这边还是不可能..

Unlike class component's this.setState , function component's useState state updater function doesn't take a second callback argument to be called after any state update.与 class 组件的this.setState不同,function 组件的useState state 更新程序 function 不会在任何 state 更新调用第二个回调参数。

What you are doing is enqueueing a state update and passing extraneous arguments, one of which is a function that you are immediately invoking, and passing any return value to setState , which will be ignored.您正在做的是排队 state 更新并传递无关的 arguments,其中之一是您立即调用的 function,并将任何返回值传递给setState ,这将被忽略。

setState(..., setCallback()) // setCallback invoked and result passed

Use an useEffect hook with a dependency on the state to log any state updates.使用依赖于 state 的useEffect挂钩来记录任何 state 更新。

const onClickCallback = () => {
  setState(...);
};

React.useEffect(() => {
  console.log(State) // this prints the updated state value
  if(state === something){
      ....
  }
}, [state, /* add other dependencies here */]);

useEffect with dependency array acts as an equivalent to componentDidMount and componentDidUpdate . useEffect与依赖数组相当于componentDidMountcomponentDidUpdate It's the componentDidUpdate lifecycle being used above to "react" to the state update and trigger a side-effect.上面使用的componentDidUpdate生命周期对 state 更新做出“反应”并触发副作用。

First第一的

This matter has nothing to do with React, your approach would have caused the setCallback() function to be executed first.这件事与 React 无关,你的做法会导致setCallback() function 先执行。

I edit your code and demo result:我编辑你的代码和演示结果:

 const onClickCallback = () => { // Here will run setCallback function before setState function. setState('...', setCallback()) } const setCallback = () => { console.info('run setCallback') } const setState = () => { console.info('run setState') } onClickCallback()

Second第二

Answer your question, you can use useEffect to achieve your goals.回答你的问题,你可以使用useEffect来实现你的目标。

Simple example:简单示例:

 const {useState, useEffect} = React; const DemoComponent = (props) => { const [state, setState] = useState('initialState') useEffect(() => { if (state === 'something') { console.info('state:' + state) } }, [state]) const onClickCallback = () => { setState('something') } return ( <div> <button onClick={onClickCallback}>Click</button> </div> ); } ReactDOM.render( <DemoComponent />, document.getElementById("root") );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.1/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.1/umd/react-dom.production.min.js"></script> <div id="root"></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM