prosource

Redux 연결 컴포넌트는 재렌더 타이밍을 어떻게 알 수 있습니까?

probook 2023. 3. 9. 22:08
반응형

Redux 연결 컴포넌트는 재렌더 타이밍을 어떻게 알 수 있습니까?

제가 뭔가 명백한 것을 놓치고 있는 것 같아서 마음을 정리하고 싶습니다.

을 사용하다
에는 '성분.states&props 중.statesetState전체 컴포넌트를 다시 장착합니다. props대부분 읽기 전용이며 업데이트는 의미가 없습니다.

스토어에 에서는 리덕스 스토어에 .store.subscribe(render)스토어가 갱신될 때마다 다시 표시됩니다.

react-suplex에는 도우미가 있다.connect()트리의 이 있음)와를 actionCreators로 삽입합니다.props via트음 음음음음음음 같은 것을 합니다.

const TodoListComponent = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)

, 이 .setState에 필수불가결한TodoListComponent 변경에 , 는 어떤 것도 수 state ★★★★★★★★★★★★★★★★★」setState( 「」의)TodoList 있어요하다

const TodoList = ({ todos, onTodoClick }) => (
  <ul>
    {todos.map(todo =>
      <Todo
        key={todo.id}
        {...todo}
        onClick={() => onTodoClick(todo.id)}
      />
    )}
  </ul>
)

제가 놓치고 있는 것에 대해 올바른 방향으로 안내해 주실 수 있나요?

추신: redux 패키지에 번들된 ToDo 목록의 예를 따르고 있습니다.

connect함수는 스토어에 가입하는 래퍼 컴포넌트를 생성합니다.작업이 디스패치되면 래퍼 컴포넌트의 콜백이 통지됩니다. 후, 「」, 「」를 합니다.mapState이 시간의 결과 개체와 전회의 결과 개체를 얕은 간격으로 변환합니다(따라서 같은 값으로 redux 스토어 필드를 다시 쓰는 경우 재실행은 트리거되지 않습니다).결과가 다르면 결과를 "실제" 컴포넌트에 소품으로 전달합니다.

는 Dan Abramov의 위대한 .connect(connect.display)에서는 최적화 작업을 전혀 보여주지 않지만 기본 아이디어를 보여줍니다.또한 관련 아이디어를 논의하는 Redux 퍼포먼스에 대한 여러 기사에 대한 링크도 있습니다.

갱신하다

React-Redux v6.0.0은 연결된 컴포넌트가 저장소에서 데이터를 수신하는 방법에 대해 몇 가지 중요한 내부 변경을 가했습니다.

으로서, 는 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★connectAPI와 API의 내부 기능 및 시간이 지남에 따라 API가 어떻게 변화했는지:

Idiomatic Redux:리액트 리덕스의 역사와 구현

내 대답은 약간 엉뚱한 것이다.그것은 내가 이 직책을 맡게 된 문제를 밝혀준다.제 경우 앱은 새로운 소품을 받았지만 리렌더링이 되지 않은 것 같습니다.
React devs는 이 질문에 대해 (스토어가) 변이되면 99%가 리액션이 재렌더되지 않는다는 선율에 대한 답변을 가지고 있었습니다.하지만 나머지 1%에 대해서는 아무것도 없습니다.돌연변이는 여기서 일어나지 않았다.


TLDR;

componentWillReceiveProps '이러다'가state새로운 것과 동기화된 상태를 유지할 수 있다props.

원스 원스 원스state업데이트하면 이 다시 다운로드 됩니다!


이 ★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★state.props수 , 「」는 갱신할 수 없습니다.state안 그럴 테니 재검사는 안 돼

는 ★★★★★★★★★★★★★★★★★★★★★★★★★.state props redex에서 store it it it it it it it it it it it it it it it it it it it it it it it it it it it it it it it it . . . it 에서 가져왔습니다.componentDidMountmapStateToPropsmapStateToProps를 되어 있기 스토어를 했을 때 .그러나 페이지는 렌더링되지 않았고 상태는 여전히 빈 문자열로 가득했습니다.

예를 들어 사용자가 저장된 URL에서 "포스트 편집" 페이지를 로드했다고 가정합니다.'할 수 있다'에할 수 있습니다.postIdurl에는 .store아, 、 그네 、 러니가와와 。구성 요소이기 되는 모든 는 관리된 구성 요소에 .표시하는 모든 데이터는 다음 위치에 있습니다.state.

사용하여 는 redex입니다.connected, 하지만 앱은 변경 사항을 반영하지 않았습니다. 보면, ★★★★★★★★★★★★★★★★★★★★.props수신되었지만 앱이 업데이트되지 않았습니다. state업데이트되지 않았습니다.

②번.props전파되지만 " " "는 " " 입니다.state 할 예요. 요.state갱신할 수 있습니다.

안 요.render() , , , , 입니다.componentDidMount벌써 끝났네요.

componentWillReceiveProps 할 수 있습니다.statepropdiscloss.discloss 。

사용 예:

componentWillReceiveProps(nextProps){
  if (this.props.post.category !== nextProps.post.category){
    this.setState({
      title: nextProps.post.title,
      body: nextProps.post.body,
      category: nextProps.post.category,
    })
  }      
}

수십 개의 다른 게시물, 블로그 및 저장소에서 언급하지 못한 솔루션에 대해 저를 일깨워준 이 기사에 큰 박수를 보내야 합니다.이 문제에 대한 답을 찾는 데 어려움을 겪고 있는 다른 사람은 다음과 같습니다.

ReactJs 컴포넌트의 라이프 사이클 방법 - 상세 정보

componentWillReceiveProps입니다.stateprops신합니니다다

(Once)state업데이트, 다음으로 필드state 재검색을 해라!

이 답변은 Brian Vaughn의 "You Usply Don Need Derived State"(2018년 6월 7일)라는 제목의 기사를 요약한 것입니다.

소품에서 상태를 도출하는 것은 모든 형태의 반패턴이다. 것을 하는 것도 됩니다.componentWillReceiveProps 최신 버전인 "" " " " " "getDerivedStateFromProps.

소품에서 상태를 도출하는 대신 다음 해결책을 고려하십시오.

2가지 베스트 프랙티스 권장 사항

Recommendation 1. Fully controlled component
function EmailInput(props) {
  return <input onChange={props.onChange} value={props.email} />;
}
Recommendation 2. Fully uncontrolled component with a key
// parent class
class EmailInput extends Component {
  state = { email: this.props.defaultEmail };

  handleChange = event => {
    this.setState({ email: event.target.value });
  };

  render() {
    return <input onChange={this.handleChange} value={this.state.email} />;
  }
}

// child instance
<EmailInput
  defaultEmail={this.props.user.email}
  key={this.props.user.id}
/>

어떤 이유로든 권장사항이 고객의 상황에 맞지 않을 경우 두 가지 대안이 있습니다.

Alternative 1: Reset uncontrolled component with an ID prop
class EmailInput extends Component {
  state = {
    email: this.props.defaultEmail,
    prevPropsUserID: this.props.userID
  };

  static getDerivedStateFromProps(props, state) {
    // Any time the current user changes,
    // Reset any parts of state that are tied to that user.
    // In this simple example, that's just the email.
    if (props.userID !== state.prevPropsUserID) {
      return {
        prevPropsUserID: props.userID,
        email: props.defaultEmail
      };
    }
    return null;
  }

  // ...
}
Alternative 2: Reset uncontrolled component with an instance method
class EmailInput extends Component {
  state = {
    email: this.props.defaultEmail
  };

  resetEmailForNewUser(newEmail) {
    this.setState({ email: newEmail });
  }

  // ...
}

redux만이 하는 일은 스토어 상태가 변경되었을 때 component를 호출하는 것입니다.컴포넌트가 변이된 상태에 의존하여 컴포넌트를 강제로 업데이트해야 하는 경우 다음과 같이 됩니다.

1-store 상태 변경-2-call(componentWillRecieveProps(()=>{3-component 상태 변경}))

언급URL : https://stackoverflow.com/questions/40386128/how-does-a-redux-connected-component-know-when-to-re-render

반응형