programing

모든 플랫폼에서 공유 싱글톤 구성 요소를 만드는 방법은 무엇입니까?

itmemos 2023. 8. 15. 10:48
반응형

모든 플랫폼에서 공유 싱글톤 구성 요소를 만드는 방법은 무엇입니까?

LoadingMask라는 React 구성 요소를 생성하려고 합니다. 여기서 (상태에 따라) 어떤 구성 요소에서도 로드 마스크를 표시할 수 있는지 여부를 확인할 수 있습니다.아이디어는 아약스 호출 전에 그것을 보여주고, 내가 데이터를 받은 후에 숨기는 것입니다.

두 개의 마스크를 동시에 표시하지 않기 때문에 한 구성 요소가 요청을 하고 다른 구성 요소가 다른 요청을 생성하는 경우 "마스크 카운터"에 1을 추가하고 요청이 완료되면 하나를 감산합니다.카운터가 0이면 Loading Mask를 숨겨야 합니다.

이 작업을 수행하려면 전체 플랫폼을 통해 공유할 수 있는 "싱글턴" 구성 요소를 만들어야 합니다. 따라서 LoadingMask는 하나뿐입니다.또한 모든 구성 요소에 마스크를 숨기거나 표시하기 위해 이벤트를 보내는 것은 좋지 않다고 생각합니다.

아이디어 있어요?

구성 요소 간에 데이터를 공유하려면 다음을 수행합니다.

  • 리덕스와 같은 lib를 사용하고 마스크 로더 상태를 공유 저장소에 유지합니다.
  • 루트 구성 요소에서 컨텍스트 대응 api를 사용하고 로더 상태를 모든 자식에게 공유합니다.아래 예를 참조하십시오.

class Application extends React.Component {
  constructor() {
    super();
    
    this.state = {
      nbTasks: 0
    };
    
    this.addTask = this.addTask.bind(this);
    this.removeTask = this.removeTask.bind(this);
    this.isLoading = this.isLoading.bind(this);
  }
  
  addTask() {
    this.setState(prevState => ({
      nbTasks: prevState.nbTasks + 1
    }));
  }
  
  removeTask() {
    this.setState(prevState => ({
      nbTasks: prevState.nbTasks - 1
    }));
  }
  
  isLoading() {
    return this.state.nbTasks > 0;
  }
  
  getChildContext() {
    return {
      addTask: this.addTask,
      removeTask: this.removeTask,
      isLoading: this.isLoading
    };
  }
  
  render() {
    return (
      <div>
        <ComponentX />
        <ComponentY />
        <LoadingMask />
      </div>
    );
  }
}

Application.childContextTypes = {
  addTask: PropTypes.func,
  removeTask: PropTypes.func,
  isLoading: PropTypes.func
};

const LoadingMask = (props, context) => (
  context.isLoading()
    ? <div>LOADING ...</div>
    : null
);

LoadingMask.contextTypes = {
  isLoading: PropTypes.func
};

class ComponentX extends React.Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      message: 'Processing ...'
    };
  }
  
  componentDidMount() {
    this.context.addTask();
    
    setTimeout(() => {
      this.setState({
        message: 'ComponentX ready !'
      });
      
      this.context.removeTask();
    }, 3500);
  }
  
  render() {
    return (
      <div>
        <button disabled>{this.state.message}</button>
      </div>
    );
  }
}

ComponentX.contextTypes = {
  addTask: PropTypes.func,
  removeTask: PropTypes.func
};

class ComponentY extends React.Component {
  constructor(props, context) {
    super(props, context);
    
    this.state = {
      message: 'Processing ...'
    };
  }
  
  componentDidMount() {
    this.context.addTask();
    
    setTimeout(() => {
      this.setState({
        message: 'ComponentY ready !'
      });
      
      this.context.removeTask();
    }, 6000);
  }
  
  render() {
    return (
      <div>
        <button disabled>{this.state.message}</button>
      </div>
    );
  }
}

ComponentY.contextTypes = {
  addTask: PropTypes.func,
  removeTask: PropTypes.func
};

ReactDOM.render(
  <Application />,
  document.getElementById('app')
);
<script src="https://unpkg.com/prop-types/prop-types.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>

<div id="app"></app>

저는 이 도서관의 중간 사용이 간단하고, 강력하며, 유용하다는 것을 알았습니다.기능적 구성요소 내에서 데이터를 공유하기 위한 중복제거의 복잡성을 제거합니다.

import React, { useState, useCallback } from 'react';
import { useBetween } from 'use-between';

컨텍스트/세션.ts

  export const useShareableState = () => {
      const [count, setCount] = useState(0);
      const inc = useCallback(() => setCount(c => c + 1), []);
      const dec = useCallback(() => setCount(c => c - 1), []);
      return {
        count,
        inc,
        dec
      };
    };

앱.tsx

import { useBetween } from 'use-between';
import { useShareableState } from './src/Context/Session'
const useSharedCounter = () => useBetween(useShareableState);

const Count = () => {
  const { count } = useSharedCounter();
  return <p>{count}</p>;
};

const Buttons = () => {
  const { inc, dec } = useSharedCounter();
  return (
    <>
      <button onClick={inc}>+</button>
      <button onClick={dec}>-</button>
    </>
  );
};

const App = () => (
  <>
    <Count />
    <Buttons />
    <Count />
    <Buttons />
  </>
);

export default App;

언급URL : https://stackoverflow.com/questions/44726316/how-to-create-shared-singleton-components-across-all-the-platform

반응형