programing

react.createContext 포인트 of defaultValue?

oldcodes 2023. 2. 28. 23:46
반응형

react.createContext 포인트 of defaultValue?

React 16 Context 문서 페이지에는 다음과 같은 예가 있습니다.

const defaultValue = 'light'
const SomeContext = React.createContext(defaultValue)

const startingValue = 'light'
const App = () => (
  <SomeContext.Provider theme={startingValue}>
    Content
  </SomeContext.Provider>
)

아무래도...defaultValue쓸모없기 때문입니다.startingValue다른 것을 설정하거나 설정하지 않음(즉,undefined)는 덮어씁니다.괜찮아, 그래야지.

하지만 그게 무슨 의미가 있죠?defaultValue?

변하지 않는 정적 콘텍스트를 원하는 경우 다음과 같은 작업을 수행할 수 있고 프로바이더를 통해defaultValue

const App = () => (
  <SomeContext.Provider>
    Content
  </SomeContext.Provider>
)

프로바이더가 없는 경우defaultValue인수는 함수에 사용됩니다.createContext컴포넌트를 포장하지 않고 단독으로 테스트하거나 프로바이더와 다른 값으로 테스트하는 경우 유용합니다.


코드 샘플:

import { createContext, useContext } from "react";

const Context = createContext( "Default Value" );

function Child() {
  const context = useContext(Context);
  return <h2>Child1: {context}</h2>;
}

function Child2() {
  const context = useContext(Context);
  return <h2>Child2: {context}</h2>;
}

function App() {

  return (
    <>
      <Context.Provider value={ "Initial Value" }>
        <Child /> {/* Child inside Provider will get "Initial Value" */}
      </Context.Provider>
        <Child2 /> {/* Child outside Provider will get "Default Value" */}
    </>
  );
}

Codesandbox 데모

위의 @tiomno에서 답변을 완료하기 위해 TypeScript를 사용할 때의 일반적인 설정을 공유합니다. 왜냐하면 최종 검색자는 실제로 다음 항목을 찾고 있기 때문입니다.

interface GridItemContextType {
    /** Unique id of the item */
    i: string;
}
const GridItemContext = React.createContext<GridItemContextType | undefined>(
    undefined
);

export const useGridItemContext = () => {
    const gridItemContext = useContext(GridItemContext);
    if (!gridItemContext)
        throw new Error(
            'No GridItemContext.Provider found when calling useGridItemContext.'
        );
    return gridItemContext;
};

이 시나리오에서는 훅을 사용하여 보다 안전하게 입력할 수 있습니다.undefined defaultValue는 프로바이더의 셋업을 잊어버리는 것을 방지합니다.

내 의견:

켄트 C의 이 유익한 기사를 읽고 나서.dods as normal :) useContext에서 반환된 값을 디스트럭처 할 때 defaultValue가 도움이 된다는 것을 알게 되었습니다.

defaultValue를 사용하지 않고 코드베이스의 한쪽 구석에 콘텍스트를 정의합니다.

const CountStateContext = React.createContext() // <-- define the context in one corner of the codebase without defaultValue

컴포넌트에서 다음과 같이 사용합니다.

const { count } = React.useContext(CountStateContext)

JS는 분명히 말할 것이다.TypeError: Cannot read property 'count' of undefined

그러나 그렇게 하지 않고 default Value를 완전히 피할 수 있습니다.

시험에 관해서, 우리 선생님 켄트씨는 다음과 같이 말하고 있습니다.

React 문서에서는 기본값을 제공하는 것이 "컴포넌트를 랩하지 않고 격리하여 테스트하는 데 도움이 될 수 있다"고 제안합니다.이 기능을 통해 이러한 작업을 수행할 수 있는 것은 사실이지만, 컴포넌트를 필요한 컨텍스트로 감싸는 것보다 더 낫다는 것에는 동의하지 않습니다.어플리케이션에서는 하지 않는 것을 테스트에서 실행할 때마다 테스트에 의한 신뢰도가 저하된다는 것을 기억하십시오.

TypeScript의 추가 기능.defaultValue를 사용하지 않으려면 다음을 수행하여 쉽게 보풀을 즐길 수 있습니다.

const MyFancyContext = React.createContext<MyFancyType | undefined>(undefined)

나중에 추가 유효성 검사만 추가하면 MyFancyContext ===이(가) 정의되지 않은 경우를 다뤘는지 확인할 수 있습니다.

  • MyFancyContext?'디폴트'
  • MyFancy Context?Not That Fancy Property(That Fancy 속성)

기타

useReducer 훅을 사용하여 기본값을 설정할 수 있습니다.다음 두 번째 인수가 기본값입니다.

import React, { createContext, useReducer } from "react";
import { yourReducer } from "./yourReducer";

export const WidgetContext = createContext();

const ContextProvider = (props) => {

  const { children , defaultValues } = props;
 
  const [state, dispatch] = useReducer(yourReducer, defaultValues);

  return (
    <WidgetContext.Provider value={{ state, dispatch }}>
      {children}
    </WidgetContext.Provider>
  );
};

export default ContextProvider;

// 구현

   <ContextProvider
                  defaultValues={{
                    disabled: false,
                    icon: undefined,
                    text: "Hello",
                    badge: "100k",
                    styletype: "primary",
                    dir: "ltr",
                    }}
                >
    </ContextProvider>
    

언급URL : https://stackoverflow.com/questions/49949099/react-createcontext-point-of-defaultvalue

반응형