programing

Reactjs에 setState()의 동기 대체가 있습니까?

css3 2023. 3. 11. 09:19

Reactjs에 setState()의 동기 대체가 있습니까?

문서의 설명에 따르면 다음과 같습니다.

setState()는 this.state를 즉시 변환하지 않고 보류 상태의 천이를 만듭니다.이 메서드를 호출한 후 this.state에 액세스하면 기존 값이 반환될 수 있습니다.

setState에 대한 콜의 동기 동작은 보증되지 않으며 성능 향상을 위해 콜이 배치될 수 있습니다.

이왕이면setState()는 비동기이며 동기 퍼포먼스에 대해서는 보증하지 않습니다. 다른 요?setState()크로로싱

예를들면

//initial value of cnt:0
this.setState({cnt:this.state.cnt+1})
alert(this.state.cnt);    //alert value:0

★★★★★★★★★★★★★★★★★.alert에 그 을 줄 수 있을까요?라서 대대 ?? ??? ????alert value:1를 사용합니다.setState().

Stackoverflow에 관한 질문은 이 질문과 비슷하지만 정답을 찾을 수 있는 곳은 없습니다.

매뉴얼에서 읽은 바와 같이 동기화할 수 있는 다른 방법은 없습니다.이유는 퍼포먼스 향상입니다.

그러나 상태를 변경한 후 작업을 수행하고자 할 경우 다음을 통해 작업을 수행할 수 있습니다.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
     x: 1
    };
    
    console.log('initial state', this.state);
  }
  
  updateState = () => {
   console.log('changing state');
    this.setState({
      x: 2
    },() => { console.log('new state', this.state); })
  }
  
  render() {
    return (
      <div>
      <button onClick={this.updateState}>Change state</button>
    </div>
    );
   
  }
}

ReactDOM.render(
  <MyComponent />,
  document.getElementById("react")
);
<div id="react"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

쌈을 요.setState 이 함수는 약속을 는 약속을 반환하는 함수입니다.await키워드를 지정하면 코드가 상태가 적용될 때까지 대기하게 됩니다.

개인적으로는, 이것을 실제 코드로 하지 않고, 스테이트 업데이트 후에 실행하고 싶은 코드를 코드에 넣습니다.setState콜백

그럼에도 불구하고, 여기 예가 있다.

class MyComponent extends React.Component {

    function setStateSynchronous(stateUpdate) {
        return new Promise(resolve => {
            this.setState(stateUpdate, () => resolve());
        });
    }

    async function foo() {
        // state.count has value of 0
        await setStateSynchronous(state => ({count: state.count+1}));
        // execution will only resume here once state has been applied
        console.log(this.state.count);  // output will be 1
    }
} 

는 foo입니다.await하면, 실행이 해, 반환되는 은 「미국의 약속」, 「미국의 약속」, 「미국의 약속」이 .setStateSynchronous문제는 이 ''에 합니다.이것은 콜백이 에 전달된 후에만 발생합니다.setState가 호출됩니다.이것은 스테이트가 적용되고 있는 경우에만 발생합니다.하는 것은 「」입니다.console.log상태 갱신이 적용되면, 스테이트 갱신이 적용됩니다.

비비 / 동기기 :
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_functionhttpsdeveloper.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/awaithttpsdeveloper.mozilla.org/en-US/docs/Web//Reference/Operators/await

이것이 필요한 경우 setState 함수에서 콜백을 사용할 것을 권장합니다(또한 기능적인 setState를 사용할 것을 권장합니다).

상태가 갱신되면 콜백이 호출됩니다.

예를 들어 다음과 같습니다.

//initial value of cnt:0
this.setState(
    (state) => ({cnt: state.cnt+1}),
    () => { alert(this.state.cnt)}
)

https://facebook.github.io/react/docs/react-component.html#setstate에 기재되어 있는 문서를 참조해 주세요.

주의: 공식 문서에는 "일반적으로 이러한 로직에는 componentDidUpdate()를 사용하는 것이 좋습니다."라고 나와 있습니다.

될 때 갱신합니다. 리액트는 리액트를 배치하는 등합니다.setState이치노를 수음음음음음음음음음음음음음음음음 a it it it it it it it 로 넘길 수 로울 수 .setState대신 이전 상태를 사용하기 때문에 이전 상태를 잘 알고 새 상태를 선택할 수 있습니다.

ReactDOM에서 flushSync를 사용하여 react docs에서 권장하는 대로 상태를 동기적으로 업데이트할 수 있습니다.

https://reactjs.org/docs/react-component.html

이상하게 들릴 수 있지만 setState는 동기적으로 반응하여 동작할 수 있습니다.어떻게요?이것은 제가 그것을 증명하기 위해 만든 POC입니다.

유일한 앱 JS 코드를 붙여넣는 중입니다.

제가 뭔가 놓치고 있는 것 같습니다만, 실제로 제 어플리케이션에서 일어나고 있던 일이었습니다.그때 이 효과를 알게 되었습니다.

내가 모르는 리액트에서 이런 행동이 예상되면 정정해 주세요.메인 스레드에 여러 setState가 있는 경우 setState는 메인 메서드의 모든 setState를 조합하여 배지를 실행합니다.한편, 같은 것이 비동기 함수 내부에 들어가는 경우는 시나리오가 다릅니다.

import React, { Component } from 'react';
import './App.css';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: 0
    }
    this.asyncMethod = this.asyncMethod.bind(this);
    this.syncMethod = this.syncMethod.bind(this);
  }

  asyncMethod() {
    console.log("*************************")
    console.log("This is a async Method ..!!")
    this.setState({
      counter: this.state.counter + 1
    }, () => {
      console.log("This is a async Method callback of setState. value of counter is---", this.state.counter);
    })
    console.log("This is a async Method on main thread. value of counter is---", this.state.counter);
    console.log("*************************")
  }

  syncMethod() {
    var that = this;
    console.log("*************************")
    console.log("This is a sync Method ..!!")
    that.setState({counter: "This value will never be seen or printed and render will not be called"});
    that.setState({counter: "This is the value which will be seen in render and render will be called"});
    setTimeout(() => {
      that.setState({counter: "This is part is synchronous. Inside the async function after this render will be called"});
      console.log("setTimeout setState");
      that.setState({counter: "This is part is aslso synchronous. Inside the async function after this render will be called"});
    }, 10)
    console.log("This is a sync Method on Main thread. value of counter is---", this.state.counter);
    console.log("*************************")
  }

  render() {
    console.log("Render..!!",this.state.counter);
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
        </header>
          <button onClick={this.asyncMethod}>AsyncMethod</button>
          <button onClick={this.syncMethod}>SyncMethod</button>
      </div>
    );
  }
}

export default App;

대신 리액트 훅 사용:

function MyComponent() {
  const [cnt, setCnt] = useState(0)

  const updateState = () => {
    setCnt(cnt + 1)
  }

  useEffect(() => {
    console.log('new state', cnt)
  }, [cnt])

  return (
    <div>
      <button onClick={updateState}>Change state</button>
    </div>
  )
}

는 리액트를 리액트를 호출할 수 .setState에 코드를 내 my로 setTimeout(() => {......this.setState({ ... });....}, 0); .부터setTimeout큐의 가 그 된 JavaScript에 수 .setState콜(큐 끝에 추가됩니다).

기능 컴포넌트에서는 다음과 같이 합니다.

const handleUpdateCountry(newCountry) {
    setIsFetching(() => true);
    setCompanyLocation(() => newCountry);
    setIsFetching(() => false);
}

제가 틀렸다면 정정해 주세요. 하지만 제가 아는 한 이것은 동기적이고 제 상황에서도 잘 작동했습니다.

네, 동기 setState를 작성할 수 있는 방법이 있습니다.근데 퍼포먼스가 좀 안 좋을 수도 있어요예를 들면 저희가

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
     data: 0
    };
  }

  changeState(){
   console.log('in change state',this.state.data);
   this.state.data = 'new value here'
   this.setState({});
   console.log('in change state after state change',this.state.data);
  }

  render() {
    return (
      <div>
      <p>{this.state.data}</p>
      <a onClick={this.changeState}>Change state</a>
    </div>
    );

  }
}  

이 예에서는 먼저 상태를 변경한 후 구성 요소를 렌더링합니다.

- 방법이 - 네, 리액션은 동기화 방법이 없습니다. - 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 맞다.setState.

하는 방법도 있습니다.createRef ★★★★★★★★★★★★★★★★★」useRef상태 대신 )를 사용합니다.

//initial value of cnt:0
const cnt = React.createRef(0); //or React.useRef(0);
cnt.current++;
alert(cnt.current); //output: 1

지금까지 저에게 가장 좋은 해결책은 콜백 기능을 사용하는 것입니다.

this.setState({cnt:this.state.cnt+1},() =>{
  // other task which we want to run synchronously
  alert(this.state.cnt); 
})

react의 공식 문서에 따르면 setState는 두 번째 인수로 콜백 함수를 전달함으로써 동기화할 수 있습니다.

언급URL : https://stackoverflow.com/questions/42018342/is-there-a-synchronous-alternative-of-setstate-in-reactjs