首页 > 解决方案 > How can I avoid having to check undefined context values in my children when using React Context?

问题描述

I have the following:

type ExploreState = {
  loading: boolean;
  posts?: Post[] // array of objects, has id and some other attrs
}

const ExploreStateContext = React.createContext<ExploreState>({
  loading: true
});

const ExploreStateProvider: React.FunctionComponent = (props) => {
  const [loading, setLoading] = React.useState(true);
  const [posts, setPosts] = React.useState<Post[]>();

  React.useEffect(() => {
    // fetch posts
    setPosts(posts);
    setLoading(false);
  }, []);

  if (loading) { return <div>Loading</div> }

  return (
    <ExploreStateContext.Provider value={{ loading, posts}}>
      {props.children} 
    </ExploreStateContext.Provider>
}

Now, if I use this context in some child component, I run into an issue where I have to check if posts is undefined which is really annoying.

const { posts } = React.useContext(ExploreStateContext)

posts.map(doSomething) // posts is possibly undefined!!!

Is there a good way to avoid this undefined checking?

标签: reactjstypescript

解决方案


可能是您正在寻找可选的链接运算符

你这样使用posts?.map(post => ...)


推荐阅读