React 애플리케이션에서 사용자를 리디렉션하는 모범 사례는 무엇인가?
나는 대응 애플리케이션에서 사용자 리디렉션과 관련된 훨씬 더 많은 사례를 보아왔고 모든 사례는 솔루션에 대한 다른 접근법일 뿐이었다."이런 행동에서 리디렉션이 발생한 사례도 있다.
export const someAction = (values, history) => async dispatch => {
const res = await someAsyncOperation(props);
history.push('/home');
dispatch(someAction);
}
이 예에서 history object(폼 react-router)는 react 구성 요소로 전달되고 있다.나로서는 이런 접근은 용납되지 않는다.리액터 로터로부터의 특별한 리다이렉트도 있다.
그 후 나는 이미 많은 기사를 뒤져 아무것도 찾을 수가 없었다.그렇다면, 당신이 생각하기에, 방향을 바꾸는 가장 좋은 방법은 무엇이며, 그러한 종류의 과정을 어디서 처리해야 하는가?
반응에서 일반적으로 다음에서 리디렉션을 수행함componentDidUpdate
구성 요소 중 하나, 둘, 셋, 넷, 넷, 넷, 넷, 넷.
비동기 동작의 경우 Redex 저장소에 저장된 플래그(일반적으로 다음과 같은 부울)를 확인하십시오.isFetching
,isCreating
,isUpdating
, 등, 액션에 의해 수정될 것이다.
간단한 예:
class EditUser extends Component {
compondentDidUpdate(prevProps) {
if (prevProps.isUpdating && !this.props.isUpdating) {
// ↑ this means that the async call is done.
history.push('/users')
}
}
updateUser() {
const modifiedUser = // ...
this.props.updateUser(modifiedUser)
// ↑ will change state.users.isUpdating from false to true during the async call,
// then from true to false once the async call is done.
}
render() {
// ...
<button onClick={this.updateUser}>Update</button>
// ...
}
}
const mapStateToProps = (state, props) => ({
userToEdit: state.users.items.find(user => user.id === props.userId)
isUpdating: state.users.isUpdating,
})
const mapActionsToProps = {
updateUser: usersActions.updateUser,
}
export default connect(mapStateToProps, mapActionsToProps)(EditUser)
다음 단계는 일반적으로 Redex 저장소에 다른 플래그를 추가하여 비동기 호출의 성공 여부를 추적하는 것이다(예:state.users.APIError
API에 의해 반환된 오류를 보관할 수 있는 .그런 다음 오류가 없는 경우에만 리디렉션을 수행하십시오.
우리는 대부분 사용자가 로그인한 시점이나 로그아웃한 시점 때문에 사용자를 리디렉션한다.예를 들어, 기본 요구 사항사용자가 로그인했는지 여부를 확인하고 다른 위치로 리디렉션하려면 HORK 구성 요소를 작성하십시오.
import React, { Component } from 'react';
import { connect } from 'react-redux';
export default ChildComponent => {
class ComposedComponent extends Component {
componentDidMount() {
this.shouldNavigateAway();
}
componentDidUpdate() {
this.shouldNavigateAway();
}
shouldNavigateAway() {
if (!this.props.auth) {
this.props.history.push('/');
}
}
render() {
return <ChildComponent {...this.props} />;
}
}
function mapStateToProps(state) {
return { auth: state.auth.authenticated };
}
return connect(mapStateToProps)(ComposedComponent);
};
사용자가 로그인했는지 확인하는 두 가지 위치가 있음
- 구성 요소가 처음 마운트될 때 - componentDidMount()에 있는 경우
- 사용자가 에 로그인하려고 할 때 로그인 또는 로그아웃 - componentDidUpdate()에서
또한 당신의 코드 샘플에서 history.push는 액션 크리에이터에 있다.액션 크리에이터는 리듀렉스 쪽에 속한다.환원제를 분리하여 보관한다.
'Programing' 카테고리의 다른 글
Ubuntu에서 pip을 통해 python3 버전의 패키지를 설치하는 방법? (0) | 2022.04.04 |
---|---|
Vue: 이미 정의된 슬롯 무시 슬롯 래퍼 (0) | 2022.04.04 |
python2에서 drit.items()와 drit.iteritems()의 차이점은 무엇인가? (0) | 2022.04.04 |
Python에서 어떻게 시간 지연을 할 수 있을까? (0) | 2022.04.04 |
http.post에서 응답을 기다리는 동안 어떻게 취소하는가? (0) | 2022.04.04 |