【发布时间】:2022-01-23 17:24:54
【问题描述】:
我正在将一个函数传递给链接中的另一个组件。在另一个组件中,我对 api 进行查询,当执行查询时,我返回上一页并执行“openFromLogin”函数。该函数执行,因为它返回console.log,但变量仍然为false。
我想这样做,以便在登录并重定向后自动打开模式。
请帮忙,谢谢:)
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import Modal from 'react-modal';
function ProductSidebarOne(props) {
const [openPricing, setOpenPricing] = useState(false);
const openFromLogin = () => {
setOpenPricing(true);
console.log("done");
}
console.log(openPricing);
return (
<>
<Link to={{ pathname: `/login`, state: { from: props.location.pathname }, openFromLogin }} className="font-orange font-semibold">Log in</Link>
<Modal
isOpen={openPricing}
shouldFocusAfterRender={false}
className="pricing-popup"
closeTimeoutMS={10}
>
<div className="modal-dialog modal-dialog-centered" role="document">
<div className="modal-content">
<div className="modal-body">
<button type="button" className="close" aria-label="Close" style={{ position: 'absolute', right: '0', top: '0' }}>
<span aria-hidden="true">×</span>
</button>
</div>
<div className="modal-footer">
<button type="button" className="btn btn-link btn-sm">Close</button>
<button type="submit" className="btn btn-primary btn-sm">Send</button>
</div>
</div>
</div>
</Modal>
</>
)
}
export default ProductSidebarOne;
import React, { useState } from 'react';
import axios from 'axios';
import { setUserSession } from '../../../../utils';
function Login(props) {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const openFromLogin = props.location.openFromLogin;
const handleLogin = (e) => {
e.preventDefault();
axios.post("api url", {
email: email,
password: password
})
.then(response => {
setUserSession(response.data);
props.history.push(props.location.state.from, openFromLogin());
});
}
return (
<div className="login-page">
<form onSubmit={handleLogin} className="mb-0">
<input type="text" className="form-control" value={email} onChange={e => setEmail(e.target.value)} />
<input type="password" className="form-control" value={password} onChange={e => setPassword(e.target.value)} />
<div className="form-footer">
<button type="submit" className="btn btn-primary">Log in</button>
</div>
</form>
</div>
)
}
export default Login;
【问题讨论】:
标签: reactjs