![](/img/trans.png)
[英]How can i initialize state by passing props from parent component to child component in ReactJS?
[英]How can you initialize a child components state from inside a parent component in react?
我有一个按钮,当单击该按钮时重定向到另一个组件,但是当单击该按钮时,我需要从父组件内部初始化子组件 state?
这是父组件中的按钮
<button variant="warning" onClick={event => window.location.href='/member'} pro={p.publisher}>
这是子组件
const Member = (props) => {
const [profile, setProfile] = useState({});
const [user, setUser] = useState({});
const {pro, notes} = props;
useEffect(async () => {
try {
h = await this.props.pro + 'hello';
console.log(h);
setUser(h);
}
} catch (e) {
console.error(e)
}
}, [])
return (
<div>
{this.user}
</div>
)
}
export default Member;
当我单击按钮时,它会重定向到子组件,但字符串不显示
如果你已经在使用react-router-dom
,那么我推荐使用Link
组件。
在此处查看文档: https://reactrouter.com/web/api/Link
以及相关的 SO 问题: React Router 的 <Link> 组件中的 state 是什么?
<Link to={{
pathname: "/member",
state: {
pro: p.publisher
}
}}
/>
并在Member
// ..
const Member = (props) => {
const [profile, setProfile] = useState("")
useEffect(()=>{
if (props.location.state && props.location.state.pro) {
setProfile(props.location.state.pro)
}
}, [props.location.state])
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.