reactjs - 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?
解决方案
可能是您正在寻找可选的链接运算符
你这样使用posts?.map(post => ...)
推荐阅读
- swift - Double 和 Float64 之间的 Swift 区别
- python - 使用日期偏移量修改数据框
- android - 如何让我的银色背景在颤动中旋转
- jquery - JQuery 提交时模型为空
- r - 如何根据多个 if 条件生成虚拟变量
- laravel - Laravel cron 作业在 localhost 中运行,但不在我与 cpanel 的共享主机中
- momentjs - 如何从当地时间获取 _i 字符串?(以 7 十进制毫秒获取本地时间的方法)
- coq - 使用 Coq 场公理
- angular - Angular/Visual Studio Code -“导出类名”上的错误
- string - 如何在 React Native 中压缩字符串?