I have a button that when clicked on redirects to another component but I need to initialize the child components state from inside the parent component when the button is clicked on?
This is the button in the parent component
<button variant="warning" onClick={event => window.location.href='/member'} pro={p.publisher}>
and this is the child component
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;
When I click on the button it redirects to the child component but the string does not show
If you are already using react-router-dom
, then I recommend using Link
component.
Check the docs here: https://reactrouter.com/web/api/Link
and related SO question here: What is a state in <Link> component of React Router?
<Link to={{
pathname: "/member",
state: {
pro: p.publisher
}
}}
/>
and in 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])
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.