react render()가 componentDidMount()보다 먼저 호출되고 있습니다.
인마이componentDidMount()
데이터를 가져오기 위해 API 호출을 하면 이 호출은 렌더링에서 사용하는 상태 개체를 설정합니다.
componentDidMount() {
const { actions } = this.props;
this.increase = this.increase.bind(this);
// api call from the saga
actions.surveyAnswersRequest();
// set breadcrumb
actions.setBreadcrumb([{ title: 'Score' }]);
actions.setTitle('Score');
this.increase();
}
렌더링 기능에서는 몇 가지 프로펠러 값을 뷰 파일에 전달합니다.
render() {
const { global, gallery, survey_answers, survey, survey_actual_answers } = this.props;
if (global.isFetching) {
return <Loading />;
}
return this.view({ gallery, survey_answers, survey, survey_actual_answers });
}
제가 안고 있는 문제는survey_actual_answers
페이지가 처음 로드되었을 때 소품이 설정되지 않았지만 페이지를 새로 고치면 소품은 데이터를 정상적으로 반환하고 나머지 스크립트는 실행됩니다.이 프로펠러 값에 대해 빈 어레이를 반환하는 것은 이번이 처음입니다.
이렇게 해서 소품을 전달했습니다.
Score.propTypes = {
actions: PropTypes.object.isRequired,
global: PropTypes.object.isRequired,
survey: PropTypes.object.isRequired,
survey_answers: PropTypes.object.isRequired,
gallery: PropTypes.object.isRequired,
survey_actual_answers: PropTypes.array.isRequired,
survey_score_system: PropTypes.array.isRequired,
survey_styles: PropTypes.object.isRequired,
survey_general_doc_data: PropTypes.object.isRequired
};
function mapStateToProps(state, ownProps) {
return {
...ownProps,
global: state.global,
gallery: state.gallery,
survey: state.survey,
survey_actual_answers: state.survey.survey_actual_answers,
survey_answers: state.survey.survey_answers,
survey_score_system: state.survey.survey_score_system,
survey_styles: state.survey.survey_styles,
survey_general_doc_data: state.survey.survey_general_doc_data,
isFetching: state.isFetching
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({
...globalActions,
...galleryActions,
...surveyActions
}, dispatch)
};
}
왜 이런 일이 일어나는지 아는 사람 있나요?componentDidMount를 전혀 호출하지 않는 것 같습니다.
이는 근본적으로 React가 작동하는 방식에 기인합니다.리액션은 빠르고 유창하며 재빠르게 느껴져야 합니다.어플리케이션은 http 요구나 비동기 코드로 막혀서는 안 됩니다.답은 라이프 사이클 방식을 사용하여 DOM을 제어하는 것입니다.
컴포넌트가 마운트된다는 것은 무엇을 의미합니까?
React 어휘를 조금 더 잘 이해하면 도움이 될 수 있습니다.컴포넌트가 마운트되면 DOM에 삽입됩니다.이때 생성자가 호출됩니다.componentWillMount는 컨스트럭터와 거의 같은 시기에 호출됩니다.componentDidMount는 첫 번째 렌더링 후에 한 번만 호출됩니다.
componentWillMount --> 렌더 --> componentDidMount
재렌더링이나 갱신과는 어떻게 다른가요?
이제 구성 요소가 DOM에 있으므로 표시되는 데이터를 변경하려고 합니다.setState를 호출하거나 부모 컴포넌트에서 새로운 소품을 전달하면 컴포넌트가 갱신됩니다.
component Will Receive Props --> component Update --> component Will Update
-->render--> componentDidUpdate
또한 http 요구는 보통 componentDidMount 및 componentDidUpdate로 이루어집니다.이는 setState를 사용하여 rerender를 트리거할 수 있기 때문입니다.
렌더링 전에 데이터를 가져오려면 어떻게 해야 할까요?
사람들이 이걸 처리하는 데는 몇 가지 방법이 있어요첫 번째 방법은 http 요청 데이터가 아직 도착하지 않은 경우 응용 프로그램을 중단하지 않도록 컴포넌트에 초기 상태를 설정하는 것입니다.http 요청이 완료될 때까지 기본 또는 빈 상태를 사용합니다.
저는 평소에는 로딩모달은 별로 좋아하지 않지만, 필요할 때도 있습니다.예를 들어 사용자가 로그인할 때 인증이 완료될 때까지 사이트의 보호 영역으로 사용자를 이동하지 않습니다.사용자가 가능한 한 많은 데이터를 프론트 로드에 로그인할 때 사용자 경험에 영향을 주지 않고 로드 모드를 사용하려고 합니다.
사이트의 나머지 사용자 환경에 영향을 주지 않으면서 구성 요소를 로드된 것으로 표시할 수도 있습니다.제가 가장 좋아하는 예 중 하나는 Airbnb 웹사이트입니다.대부분의 사이트를 사용할 수 있고 스크롤하거나 링크를 클릭할 수 있지만 '체험' 아래의 영역은 로드 상태입니다.이는 React를 사용하는 올바른 방법이며 setState 및 HTTP 요구가 componentDidMount/componentDidUpdate로 실행되는 이유입니다.
componentdidmount에서 setState를 사용하고 있습니다.내 코드:
async componentDidMount() {
danhSachMon = await this.getDanhSachMon();
danhSachMon=JSON.parse(danhSachMon);
this.setState(danhSachMon);
}
render() {
return (
<View>
<FlatList
data={danhSachMon}
showsVerticalScrollIndicator={false}
renderItem={({ item }) =>
<View >
<Text>{item.title}</Text>
</View>
}
keyExtractor={(item, index) => index.toString()}
/>
</View>
)
}
componentWillMount는 권장되지 않습니다.이제 "DidMount"를 사용해야 합니다. 렌더에서 DOM이 완료되고 변경되는 즉시 react가 다른 모든 작업을 처리합니다.
렌더에서 올바른 변수/상태/프롭을 업데이트하고 사용해야 합니다.
componentDidMount() {
const { applicationId } = this.props;
if (applicationId) {
ApplicationService.getQuotesByApplicationId(applicationId).then((response) => {
const quotes = _.get(response, 'data.data');
this.setState({
quotes,
});
});
....
}
render() {
const quotes = _.get(this.state, 'quotes', null);
return (
<div className="application">
<h4 className="application__sub">Application</h4>
<h1 className="application__title">Quote Comparison</h1>
<div className="form-wrapper">
{this.renderQuotes(quotes)}
</div>
<div />
</div>
);
}
API에서 인용문을 가져오면 API가 완료되는 즉시 해당 상태에 변수를 설정하고 렌더와 리액트가 작업을 수행합니다.
언급URL : https://stackoverflow.com/questions/45337165/react-render-is-being-called-before-componentdidmount
'sourcecode' 카테고리의 다른 글
ASP.net MVC에서 JSONP 반환 (0) | 2023.03.09 |
---|---|
urlib2 및 json (0) | 2023.03.09 |
React.js에서 리치 데이터 구조 편집 (0) | 2023.03.04 |
AngularJS 형식 JSON 문자열 출력 (0) | 2023.03.04 |
해석된 JSON에 PowerShell을 추가하는 방법 (0) | 2023.03.04 |