[英]Syncrohize react conditional rendering and typescript
In this component I trigger post loading using postsActions.getPost('1')
and put it into the redux store.在这个组件中,我使用
postsActions.getPost('1')
触发后加载并将其放入 redux 存储。 useSelector
catches it and triggers PostPage
rerender, now with header and button with onClickUse
function attached that uses post.header
along with the post object that it uses: useSelector
it and triggers PostPage
rerender, now with header and button with onClickUse
function attached that uses post.header
along with the post object that it uses:
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { postsActions } from '../../store/Posts';
import styles from './PostPage.module.scss';
const PostPage = () => {
const dispatch = useDispatch();
const post = useSelector((state) => state.post);
const onClickUse = () => {
console.log(`See? I am used only when post is rendered`);
console.log(`So it's fine if I use it here: ${post.header}`);
}
useEffect(() => {
dispatch(postsActions.getPost('1'));
}, []);
return (
<div className={styles.container}>
{
post &&
<div>
<h1>{post.header}</h1>
<button onClick={onClickUse}>Click me</button>
</div>
}
</div>
);
};
export default PostPage;
The problem is that typescript yells inside onClickUse
at me that post
can be undefined
.问题是
onClickUse
在 onClickUse 里面对我大喊那个post
可以是undefined
。 How do I then synchronize React conditional rendering functionality and typescript without hacks from this question , like !
然后我如何同步 React 条件渲染功能和 typescript 没有这个问题的黑客,比如
!
, as
etc. as
等等。
You can inline你可以内联
<div className={styles.container}>
{
post &&
<div>
<h1>{post.header}</h1>
<button onClick={() => {
console.log(`See? I am used only when post is rendered`);
console.log(`So it's fine if I use it here: ${post.header}`);
}}>Click me</button>
</div>
}
</div>
or if you don't want inline functions in render, you should create a component with not falsy post
in props and conditionally render it.或者,如果您不想在渲染中使用内联函数,则应该在 props 中创建一个带有非虚假
post
的组件并有条件地渲染它。
Typescript (in handler) knows nothing about render logic in your example Typescript(在处理程序中)对您的示例中的渲染逻辑一无所知
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.