typescript中,从上下文设置状态的setState可能为undefined。

huangapple go评论65阅读模式
英文:

typescript setState from Context is possibly undefined

问题

Typescript 报错我的 setReposlist 未定义。我感到困惑,因为我认为我之前已经使用了这个接口进行了类型定义:

export interface ReposContextInterface {
    reposList: {},
    setReposList?: Dispatch<SetStateAction<reposList>>
}
export interface SearchPageContextInterface{
    searchRepos: ReposContextInterface
}
export const SearchPageContext = createContext({} as SearchPageContextInterface);

并且我在我的 app.tsx 文件中定义了上下文:

<SearchPageContext.Provider value={{searchRepos: {reposList, setReposList}}}>

但是当我在我的 React 组件中使用上下文时,像这样:

const SearchPage = useContext(SearchPageContext);
const {searchRepos} = SearchPage;
useEffect(() => {
    const getRepos = async (username: string) => {
        const repos = await axios.get(`https://endpoint/${username}/repos`);
        if (repos) {
            const {data} = repos;
            const temp:any = {};
            temp[username] = data;
            setReposList({...reposList, ...temp});
        } else {
            setReposList({...reposList});
        }
    };
    getRepos(username);
}, []);

它会给我这个错误消息:

Cannot invoke an object which is possibly 'undefined'.ts(2722)
const setReposList: React.Dispatch<React.SetStateAction<reposList>> | undefined

请帮忙解决。谢谢。

英文:

Typescript complains that my setReposlist is undefined. I am confused because I think have previously typed using this interface:

export interface ReposContextInterface {
    reposList: {},
    setReposList?: Dispatch&lt;SetStateAction&lt;reposList&gt;&gt;
}
export interface SearchPageContextInterface{
    searchRepos: ReposContextInterface
}
export const SearchPageContext = createContext({} as SearchPageContextInterface);

and I define the context on my app.tsx:

 &lt;SearchPageContext.Provider value={{searchRepos: {reposList, setReposList}}}&gt;

but when I use the context on my react component like this:

const SearchPage = useContext(SearchPageContext);
const {searchRepos} = SearchPage;
useEffect(()=&gt;{
  
    const getRepos = async (username: string) =&gt;{
      const repos = await axios.get(`https://endpoint/${username}/repos`);
      if(repos) {
        const {data} = repos;
        const temp:any = {};
        temp[username] = data;
        setReposList({...reposList, ...temp});
      } else {
        setReposList({...reposList});
      }
    };
  getRepos(username);
    
  },[]);

it gives me this error message:
Cannot invoke an object which is possibly 'undefined'.ts(2722)
const setReposList: React.Dispatch<React.SetStateAction<reposList>> | undefined

Please help. Thank you.

答案1

得分: 1

我建议完全移除上下文类型中的可选性,并使用虚拟对象作为初始值。可以像这样做:

interface ReposContextInterface {
    reposList: {},
    setReposList: Dispatch<SetStateAction<reposList>>
}

export const SearchPageContext = createContext<ReposContextInterface>({reposList: {}, setReposList: () => null})

如果您希望保留setReposList的可选性,您可以使用可选链操作符:

setReposList?.({...reposList});
英文:

I would suggest entirely removing the optionality in the context type and using a dummy object as an initial value. Something like this:

interface ReposContextInterface {
    reposList: {},
    setReposList: Dispatch&lt;SetStateAction&lt;reposList&gt;&gt;
}

export const SearchPageContext = createContext&lt;ReposContextInterface&gt;({reposList: {}, setReposList: () =&gt; null})

If you wish to keep the optionality of the setReposList, you can use optional chaining:

setReposList?.({...reposList});

huangapple
  • 本文由 发表于 2023年5月21日 22:55:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76300503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定