【发布时间】:2021-06-12 02:22:41
【问题描述】:
我在 react js 中有一个组件来处理用户是否创建帖子。我还使用来自父组件的数据来显示用户的详细信息。就像用户的用户名一样。我遇到了问题,因为我找不到将来自组件父级的用户名分配为 useState 的一部分的方法。该值存在,但在用户提交数据后,用户名名称不包括在内。 您能向我解释或帮助我为什么价值不存在吗?
Parent Component
const userDetails = useSelector((state) => state.userLogin);
const { userData } = userDetails;
const classes = useStyles();
useEffect(() => {
if (userDetails) {
history.push();
}
}, [history, userDetails]);
return (
<FormContainer>
<Container component='div' className={classes.homepageContainer}>
<Grid item xs={12}>
<Container component='div' className={classes.userFeedCard}>
<Card className={classes.userPostFeedCard}>
<UserPost userData={userData} />
</Card>
</Container>
</Grid>
</Container>
</FormContainer>
);
};
Child Component
const UserPost = ({ userInfo }) => {
const [postInfo, setPostInfo] = useState({
username: userInfo.username,
description: '',
});
const handlePost = async (e) => {
e.preventDefault();
console.log(postInfo);
};
return (
<Container
component='div'
className={classes.userPostContainer}
style={{ padding: '0', margin: '0' }}
>
<Card className={classes.userPostCard} style={{ boxShadow: 'none' }}>
<CardContent style={{ padding: '0 0 1.5em 0' }}>
<form noValidate onSubmit={handlePost}>
<Grid container>
<Grid item xs={12}>
<TextField
variant='outlined'
id='description'
name='description'
type='text'
value={postInfo.description}
onChange={handleChange}
placeholder={`What's on your mind, ${
userInfo && userInfo.username
}`}
fullWidth
InputLabelProps={{
classes: {
root: classes.label,
focused: classes.focused,
},
}}
InputProps={{
className: classes.textfieldBg,
classes: {
root: classes.cssOutlinedInputBg,
focused: classes.cssFocused,
notchedOutline: classes.NonotchedOutline,
},
}}
/>
</Grid>
<Grid
xs={12}
container
className={classes.postPhotoContainer}
style={{ padding: '0' }}
>
<Grid xs={2} style={{ padding: '0', margin: '0' }}>
<Button
type='submit'
variant='contained'
startIcon={<SendIcon />}
style={{}}
>
Upload
</Button>
</Grid>
</Grid>
</Grid>
</form>
</CardContent>
</Card>
</Container>
);
};
【问题讨论】:
-
你总是想要一个“单一的事实来源”,所以你不应该在 state 中复制 props。只需直接使用道具中的
userInfo。 -
您在此处所做的操作将
postInfo状态的初始值 设置为包含来自道具的用户名。它不会响应父组件中的任何更改。 -
HomePage中的userInfo状态也是不必要的数据复制。你已经从 Redux 获得了这些数据。够了!它不应该存储在状态中。 -
感谢@LindaPaiste 的建议
标签: reactjs