簡體   English   中英

反應 createContext 不適用於 typescript

[英]react createContext not working with typescript

我正在嘗試對我的 React typescript 應用程序實施以下吐司管理器

https://codesandbox.io/s/react-toasts-melne?from-embed=&file=/src/contexts/ToastContext.js

我創建了一個名為toast-context.tsx的文件

import React, { useCallback, useEffect, useState, createContext } from 'react';

const ToastContext = createContext(null);

export default ToastContext;

export function ToastContextProvider({ children }) {
  const [toasts, setToasts] = useState([]);

  useEffect(() => {
    if (toasts.length > 0) {
      const timer = setTimeout(() => setToasts((toasts) => toasts.slice(1)), 6000);
      return () => clearTimeout(timer);
    }
  }, [toasts]);

  const addToast = useCallback(
    function (toast) {
      setToasts((toasts) => [...toasts, toast]);
    },
    [setToasts],
  );

  return (
    <ToastContext.Provider value={addToast}>
      {children}
      <div style={{ position: 'fixed', bottom: '1 rem', left: '1 rem' }}>
        {toasts.map((toast) => (
          <div style={{ background: 'green', color: 'white' }} key={toast}>
            {toast}
          </div>
        ))}
      </div>
    </ToastContext.Provider>
  );
}

和一個鈎子作為useToast

import { useContext } from 'react';
import ToastContext from '../contexts/toast-context';

export default function useToast() {
  return useContext(ToastContext);
}

在我的 _app.tsx 中(這是 nextjs)

  return (
    <>
      <div className="app">
        <ToastContextProvider>
          <ThemeProvider theme={theme}>
            <Component {...pageProps} />
          </ThemeProvider>
        </ToastContextProvider>
      </div>
    </>
  );
};

但是當我嘗試使用該解決方案時,它說Uncaught TypeError: addToast is not a function

export const ToastTest = () => {
  const [text, setText] = useState('');
  const addToast = useToast();

  function handleTextChange(event) {
    setText(event.target.value);
  }
  function handleClick() {
    addToast(text);
  }

  return (
    <div>
      <h1>Hello Toasts!</h1>
      <div>
        <input value={text} onChange={handleTextChange} />
      </div>
      <button onClick={handleClick}>Show toast</button>
    </div>
  );
};

我遵循了示例中的所有內容。 在示例中它可以工作,但不確定為什么它在我的代碼中不起作用。有人可以指出這個問題嗎?

當我點擊“Show toast”按鈕時,這是我遇到的錯誤

在此處輸入圖像描述

錯誤消息說這是一個“TypeError”,但實際上這與 typescript 無關。如果您嘗試調用實際上不是 function 的內容,則會發生 JavaScript 錯誤。例如,null 不是 function 並且如果您嘗試調用它,則會拋出此錯誤。

該錯誤很可能是因為您沒有在 ToastContextProvider 組件內呈現 ToastTest 組件。 您對 useToast 的調用可能會獲取默認值“null”,並在它嘗試將“null”調用為 function 時拋出此錯誤。確保您的 ToastContextProvider 是 ToastTest 組件的父級或祖父級。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM