javascript - React Redux 状态条件错误和 useEffect 依赖错误
问题描述
我有一个组件可以通过 params.id 获取单个帖子的详细信息我的标题错误未定义,但由于我有数据,redux 操作成功返回,我认为组件在接收到 redux 操作有效负载之前先加载?
const UpdatePost = ({ match, history }) => {
const postId = match.params.id;
const [title, setTitle] = useState('');
const [description, setDescription] = useState('');
const [image, setImage] = useState('');
const dispatch = useDispatch();
const postDetails = useSelector(state => state.postDetails);
const { loading, error, post } = postDetails;
const postUpdate = useSelector(state => state.postUpdate);
const {
loading: loadingUpdate,
error: errorUpdate,
success: successUpdate,
} = postUpdate;
useEffect(() => {
if (successUpdate) {
dispatch({ type: POST_UPDATE_RESET });
dispatch({ type: POST_DETAILS_RESET });
history.push('/edit/post');
} else {
console.log(post, postId);
if (!post.title || post._id !== postId) {
dispatch(listPostDetails(postId));
} else {
setTitle(post.title);
setDescription(post.description);
setImage(post.image);
}
}
}, [post, history, dispatch, postId, successUpdate]);
const submitHandler = e => {
e.preventDefault();
dispatch(
updatePost({
_id: postId,
title,
description,
image,
})
);
};
return (
<MotionBox
exit={{ opacity: 0 }}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 1 }}
bgColor={'#eaeaea'}
my="1rem"
border="2px"
borderColor="#eaeaea"
borderRadius="25px"
p={{ base: '2rem 2rem' }}
>
<Heading color={'#435943'} size="lg" pb={'1.5rem'}>
Edit User
</Heading>
{loadingUpdate && <Loader />}
{errorUpdate && <Message status="error">{errorUpdate}</Message>}
{loading && loadingUpdate ? (
<Loader />
) : error ? (
<Message status="error">{error}</Message>
) : (
<form onSubmit={submitHandler}>
<FormControl pb={'1rem'}>
<FormLabel size="md">Edit Post Title</FormLabel>
<Input
borderColor="#d4d6d5"
placeholder="Edit Post Title"
value={title}
onChange={e => setTitle(e.target.value)}
/>
</FormControl>
<FormControl pb={'1rem'}>
<FormLabel size="md">Edit Post Description</FormLabel>
<Textarea
size="md"
value={description}
onChange={e => setDescription(e.target.checked)}
placeholder="Edit Post Descrription"
/>
</FormControl>
<FormControl pb={'1rem'}>
<FormLabel size="md">Edit Post Photo</FormLabel>
<Input
size="md"
placeholder="Edit Post Photo"
value={image}
onChange={e => setImage(e.target.checked)}
/>
</FormControl>
<Button
type="submit"
my={'2rem'}
fontSize={'md'}
fontWeight={600}
color="white"
bg={'green.800'}
_hover={{
background: 'green.600',
}}
_focus={{
outline: 'none',
border: 'none',
}}
>
Update
</Button>
</form>
)}
</MotionBox>
);
};
解决方案
推荐阅读
- django - 在不可调用的 python3 django models.py 中键入错误 str
- oracle - 将 micronaut-data 与 JDBC 一起使用时如何获取 DB 序列值
- python - 在 iManage 上访问文档
- android - React-Native 禁用滑动手势以在嵌套的 StackNavigator 特定屏幕中打开抽屉
- ios - 将json数组发送到alamofire
- go - 在 golang 的地图中使用指针
- c - 为什么我总是得到负值?
- python - 为什么会出现带有 if 和 elif [ 的 SyntaxError
- jsp - 如何在从下拉列表中选择时将值插入不同的表
- github - 无法从 GitHub NPM 注册表 (npm.pkg.github.com) 通过 yarn 下载依赖项