setState 업데이트가 완료된 후 함수를 실행할 수 있습니까?
React JS는 처음입니다(예: 오늘부터 시작).어떻게 하는지 잘 모르겠어요.setState
React와 Easel JS를 조합하여 사용자 입력에 따라 그리드를 그립니다.여기 JS BIN이 있습니다.http://jsbin.com/zatula/edit?js,output
코드는 다음과 같습니다.
var stage;
var Grid = React.createClass({
getInitialState: function() {
return {
rows: 10,
cols: 10
}
},
componentDidMount: function () {
this.drawGrid();
},
drawGrid: function() {
stage = new createjs.Stage("canvas");
var rectangles = [];
var rectangle;
//Rows
for (var x = 0; x < this.state.rows; x++)
{
// Columns
for (var y = 0; y < this.state.cols; y++)
{
var color = "Green";
rectangle = new createjs.Shape();
rectangle.graphics.beginFill(color);
rectangle.graphics.drawRect(0, 0, 32, 44);
rectangle.x = x * 33;
rectangle.y = y * 45;
stage.addChild(rectangle);
var id = rectangle.x + "_" + rectangle.y;
rectangles[id] = rectangle;
}
}
stage.update();
},
updateNumRows: function(event) {
this.setState({ rows: event.target.value });
this.drawGrid();
},
updateNumCols: function(event) {
this.setState({ cols: event.target.value });
this.drawGrid();
},
render: function() {
return (
<div>
<div className="canvas-wrapper">
<canvas id="canvas" width="400" height="500"></canvas>
<p>Rows: { this.state.rows }</p>
<p>Columns: {this.state.cols }</p>
</div>
<div className="array-form">
<form>
<label>Number of Rows</label>
<select id="numRows" value={this.state.rows} onChange={ this.updateNumRows }>
<option value="1">1</option>
<option value="2">2</option>
<option value ="5">5</option>
<option value="10">10</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
<label>Number of Columns</label>
<select id="numCols" value={this.state.cols} onChange={ this.updateNumCols }>
<option value="1">1</option>
<option value="2">2</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="12">12</option>
<option value="15">15</option>
<option value="20">20</option>
</select>
</form>
</div>
</div>
);
}
});
ReactDOM.render(
<Grid />,
document.getElementById("container")
);
JSbin에서 드롭다운 중 하나를 사용하여 행 또는 열의 수를 변경해도 처음에는 아무 일도 일어나지 않습니다.다음에 드롭다운 값을 변경하면 그리드가 이전 상태의 행 및 열 값으로 그려집니다.이 일이 일어나는 이유는 제 생각엔this.drawGrid()
함수가 실행 중입니다.setState
완료했습니다.다른 이유가 있는 걸까요?
시간 내주셔서 감사합니다!
setState(updater[, callback])
는 비동기 함수입니다.
https://facebook.github.io/react/docs/react-component.html#setstate
setState가 두 번째 파라미터를 사용하여 종료된 후 함수를 실행할 수 있습니다.callback
예를 들어 다음과 같습니다.
this.setState({
someState: obj
}, () => {
this.afterSetStateFinished();
});
리액트 기능 컴포넌트의 후크에서도 같은 작업을 할 수 있습니다.
https://github.com/the-road-to-learn-react/use-state-with-callback#usage
useStateWithCallbackLazy를 확인합니다.
import { useStateWithCallbackLazy } from 'use-state-with-callback';
const [count, setCount] = useStateWithCallbackLazy(0);
setCount(count + 1, () => {
afterSetCountFinished();
});
render
매번 전화할 것이다setState
컴포넌트가 변경되었을 경우 다시 컴포넌트를 재설치합니다.콜을 로 이동했을 경우drawGrid
전화하는 것 보다update*
방법은 문제없을 겁니다.
만약 그것이 당신에게 효과가 없다면, 또한 오버로드가 있다.setState
콜백을 두 번째 파라미터로 받아들입니다.당신은 그것을 최후의 수단으로 이용할 수 있을 것입니다.
만들기setState
을 반환하다Promise
패스하는 것 외에callback
로.setState()
메서드, 랩핑할 수 있습니다.async
기능 및 사용then()
method -- 경우에 따라서는 보다 깨끗한 코드가 생성될 수 있습니다.
(async () => new Promise(resolve => this.setState({dummy: true}), resolve)()
.then(() => { console.log('state:', this.state) });
여기서 한 걸음 더 나아가서 재사용할 수 있습니다.setState
위 버전보다 나은 기능:
const promiseState = async state =>
new Promise(resolve => this.setState(state, resolve));
promiseState({...})
.then(() => promiseState({...})
.then(() => {
... // other code
return promiseState({...});
})
.then(() => {...});
리액트 16.4에서는 정상적으로 동작하지만, 이전 버전의 리액트에서는 아직 테스트하지 않았습니다.
또, 콜백 코드를 보관해 두는 것도 고려할 필요가 있습니다.componentDidUpdate
방법은 대부분의 경우 - 아마도 모든 경우에서 더 나은 방법입니다.
리액트 16.8 이후의 훅에서는, 이 조작을 간단하게 실시할 수 있습니다.useEffect
이것을 증명하기 위해 코드 샌드박스를 만들었습니다.
useEffect(() => {
// code to be run when state variables in
// dependency array changes
}, [stateVariables, thatShould, triggerChange])
기본적으로는useEffect
상태 변경과 동기화하여 캔버스를 렌더링할 수 있습니다.
import React, { useState, useEffect, useRef } from "react";
import { Stage, Shape } from "@createjs/easeljs";
import "./styles.css";
export default function App() {
const [rows, setRows] = useState(10);
const [columns, setColumns] = useState(10);
let stage = useRef()
useEffect(() => {
stage.current = new Stage("canvas");
var rectangles = [];
var rectangle;
//Rows
for (var x = 0; x < rows; x++) {
// Columns
for (var y = 0; y < columns; y++) {
var color = "Green";
rectangle = new Shape();
rectangle.graphics.beginFill(color);
rectangle.graphics.drawRect(0, 0, 32, 44);
rectangle.x = y * 33;
rectangle.y = x * 45;
stage.current.addChild(rectangle);
var id = rectangle.x + "_" + rectangle.y;
rectangles[id] = rectangle;
}
}
stage.current.update();
}, [rows, columns]);
return (
<div>
<div className="canvas-wrapper">
<canvas id="canvas" width="400" height="300"></canvas>
<p>Rows: {rows}</p>
<p>Columns: {columns}</p>
</div>
<div className="array-form">
<form>
<label>Number of Rows</label>
<select
id="numRows"
value={rows}
onChange={(e) => setRows(e.target.value)}
>
{getOptions()}
</select>
<label>Number of Columns</label>
<select
id="numCols"
value={columns}
onChange={(e) => setColumns(e.target.value)}
>
{getOptions()}
</select>
</form>
</div>
</div>
);
}
const getOptions = () => {
const options = [1, 2, 5, 10, 12, 15, 20];
return (
<>
{options.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</>
);
};
되었을 때(를 들어, 「소품」이라고 하는 것)setState
는 몇 기능을 기능을 React라고 .componentWillUpdate
★★★★★★★★★★★★★★★★★」componentDidUpdate
고객님의 경우, 단순히 추가하기만 하면 됩니다.componentDidUpdate
를 호출하는 this.drawGrid()
바와 에서는, 「코드로」, 「코드는 '코드로'입니다.componentDidUpdate
합니다.this.setState(...)
componentDidUpdate
는 inside를 합니다.this.drawGrid()
컴포넌트 라이프 사이클에 대한 자세한 내용은 React https://facebook.github.io/react/docs/component-specs.html#updating-componentwillupdate를 참조하십시오.
상태를 업데이트 할 때마다 실행하는 것이 아니라 상태를 업데이트한 후에 몇 가지 기능을 실행해야 했습니다.
★★★★★★★★★★★★★★★★★★:
const [state, setState] = useState({
matrix: Array(9).fill(null),
xIsNext: true,
});
...
...
setState({
matrix: squares,
xIsNext: !state.xIsNext,
})
sendUpdatedStateToServer(state);
서 ★★★★sendUpdatedStateToServer()
는 상태를 갱신한 후 실행하는 데 필요한 기능입니다.useEffect()를 실행하고 않기 .sendUpdatedStateToServer()
★★★★★★★★★★★★★★★★★★★★★★★★★★★
나에게 효과가 있었던 것:
const [state, setState] = useState({
matrix: Array(9).fill(null),
xIsNext: true,
});
...
...
const newObj = {
matrix: squares,
xIsNext: !state.xIsNext,
}
setState(newObj);
sendUpdatedStateToServer(newObj);
상태 갱신 후 기능에서 실행이 필요한 오브젝트를 새로 만들어 사용했을 뿐입니다.를 계속 하고 setState 함수는 setState를 계속 합니다.sendUpdatedStateToServer()
업데이트 된 상태를 받을 수 있을 것 같습니다.
여기 더 나은 구현이 있습니다.
import * as React from "react";
const randomString = () => Math.random().toString(36).substr(2, 9);
const useStateWithCallbackLazy = (initialValue) => {
const callbackRef = React.useRef(null);
const [state, setState] = React.useState({
value: initialValue,
revision: randomString(),
});
/**
* React.useEffect() hook is not called when setState() method is invoked with same value(as the current one)
* Hence as a workaround, another state variable is used to manually retrigger the callback
* Note: This is useful when your callback is resolving a promise or something and you have to call it after the state update(even if UI stays the same)
*/
React.useEffect(() => {
if (callbackRef.current) {
callbackRef.current(state.value);
callbackRef.current = null;
}
}, [state.revision, state.value]);
const setValueWithCallback = React.useCallback((newValue, callback) => {
callbackRef.current = callback;
return setState({
value: newValue,
// Note: even if newValue is same as the previous value, this random string will re-trigger useEffect()
// This is intentional
revision: randomString(),
});
}, []);
return [state.value, setValueWithCallback];
};
사용방법:
const [count, setCount] = useStateWithCallbackLazy(0);
setCount(count + 1, () => {
afterSetCountFinished();
});
컴포넌트를 작성하는 새로운 권장 방법은 기능에 의한 것이므로 클래스 컴포넌트에서 이 질문에 접근하지만 이 답변은 React v16에서 도입된 기능 후크에서 문제를 해결합니다.
import { useState, useEffect } from "react";
const App = () => {
const [count, setCount] = useState(0);
useEffect(() => console.log(count), [count]);
return (
<div>
<span>{count}</span>
<button onClick={() => setCount(count + 1)}>Click Me</button>
</div>
);
};
에서 알 수 컴포넌트입니다.단, 이 컴포넌트에서는useEffect
이 예의 훅에는 의존관계 배열(의존할 가능성이 있는 의존상태)로서두 번째 인수가 있습니다.훅은 훅이 동작하는 것은count
되면 빈 배열이 전달됩니다.useEffect
는 리슨할 종속 상태 변수가 없기 때문에 한 번만 실행됩니다.
간단하지만 효과적인 리액트 훅 가이드 - 10가지 리액트 훅 설명 | Fireship
2022 2022 2022 2022 2022
17에서는 하지 않는 것 .은 ES6입니다.ES6+는 ES6+로 동작합니다.
import React from 'react';
import useStateWithCallback from 'use-state-with-callback';
const App = () => {
const [count, setCount] = useStateWithCallback(0, count => {
if (count > 1) {
console.log('Count is larger than 1');
//or call other function
} else {
console.log('Count is less than or equal to 1');
//or call other function
}
});
const handleClick = () => {
setCount(count + 1);
};
return (
<div>
<p>{count}</p>
<button type="button" onClick={handleClick}>
Increase
</button>
</div>
);
};
export default App;
언급URL : https://stackoverflow.com/questions/34687091/can-i-execute-a-function-after-setstate-is-finished-updating
'programing' 카테고리의 다른 글
JavaScript에 RegExp.escape 함수가 있나요? (0) | 2022.10.23 |
---|---|
판다 열을 여러 열로 분할 (0) | 2022.10.22 |
MariaDB - 최대 BLOB 사이즈는? (0) | 2022.10.22 |
mysql 비밀번호 검증을 해제하려면 어떻게 해야 하나요? (0) | 2022.10.22 |
메이븐의 MOJO가 뭐죠? (0) | 2022.10.22 |