如何解决未处理的拒绝TypeError:params.setLoggedIn 不是函数
在将 SetState 从父级传递给子级时出现错误。
父组件 Index.js
const Index = () => {
const [loggedIn,setLoggedIn] = useState(false);
return (
<Router>
<NavBar user={loggedIn} />
<Switch>
<Route path="/" exact component={QuestionList} />
<Route path="/register" component={Register} />
<Route path="/login" component={Login} setLoggedIn={setLoggedIn} />
<Route path="/addquestions" component={QuestionForm} />
<Route path="/viewquestions" exact component={QuestionList} />
<Route path="/viewquestions/:id" component={QuestionList} />
<Route path="/logout" component={Logout} />
</Switch>
</Router>
);
};
子组件
const Login = (params) => {
const initialCredentials = {
email: "",password: "",};
const [credentials,setCredentials] = useState(initialCredentials);
const [isValid,setIsValid] = useState(false);
const handleInputChange = (e) => {
setCredentials({ ...credentials,[e.target.name]: e.target.value });
};
const handleFinalSubmit = (e) => {
e.preventDefault();
validateUser(credentials);
};
const validateUser = async (data) => {
const result = await loginUser(data);
if (result.data.success) {
setToken(result.data.token);
setIsValid(true);
params.setLoggedIn(true);
}
return <Redirect to={{ pathname: "/login" }} />;
};
if (isValid) return <Redirect to="/" />;
return (
<div className="container border border-gray mt-5 rounded">
<h4 className="mt-3 text-info">Login</h4>
<form action="/" className="mt-3" onSubmit={handleFinalSubmit}>
<div className="form-group">
<input
type="text"
className="form-control border border-info"
id="formGroupExampleInput2"
placeholder="Email"
name="email"
value={credentials.email}
onChange={handleInputChange}
/>
<br></br>
<input
type="password"
className="form-control border border-info"
id="formGroupExampleInput2"
placeholder="**********"
name="password"
value={credentials.password}
onChange={handleInputChange}
/>
<br></br>
<button type="submit" className="btn btn-primary">
Submit
</button>
</div>
</form>
</div>
);
};
我在子组件中有一个登录表单。当我提交表单时,我将验证用户。一旦用户有效。然后我将更新父组件的状态。 在更新父 setLoggedIn 状态时。 我收到以下错误
错误
可能是什么问题?
解决方法
您需要将 props
传递给组件而不是 Route Component
:
<Route path="/login" component={<Login setLoggedIn={setLoggedIn} />} />;
还有一个技巧是在您的 props
组件中使用 params
而不是 login
,因为它可能会与 params
{{1} 中的 react-router-dom
混淆}} 对象
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。