reactjs - React 使用 Hooks 处理链接的条件渲染
问题描述
我正在尝试根据用户登录做一些基本的条件渲染。我在登录组件中有我的事件处理程序和 axios 调用。
const Login = () => {
const handleChange = event => {
setCustomerLogin({
...customerLogin,
[event.target.name]: event.target.value
});
};
const handleSubmit = e => {
e.preventDefault();
axios
.post("/api/Authentication", customerLogin)
.then(function(response) {
setCustomerLogin(response.data);
console.log(response);
})
.catch(function(error) {
console.log(error);
});
};
我的导航栏组件现在非常基本,只是自动呈现我的 SignedOutLinks,这是我在用户登录之前显示的链接。
const Navbar = () => {
return (
<nav className="nav-wrapper blue darken-4">
<div className="container">
<Link to='/' className="brand-logo left">Cars4U</Link>
<SignedOutLinks />
</div>
</nav>
)
};
我想在 App.js 中定义我的 setCustomerLogin 函数并让我的登录组件调用这个值。到目前为止,这是我的 App.js 文件,我只是不确定如何在我的 App.js 中定义函数并在我的登录组件中设置状态
const [customerLogin, setCustomerLogin] = useState([
{ username: "", password: "" }
]);
function App() {
return(
<div className="App">
<Navbar />
<Switch>
<Route path='/login' component={Login}/>
<Route path='/signup' component={Signup}/>
</Switch>
</div>
);
}
解决方案
你可以将 state setter( setCustomerLogin
) 和 state value( )作为 propscustomerLogin
传递给你的组件:Login
const [customerLogin, setCustomerLogin] = useState([
{ username: "", password: "" }
]);
function App() {
return(
<div className="App">
<Navbar />
<Switch>
<Route path='/signup' component={Signup}/>
<Route
path="/login"
render={() =>
<Login
customerLogin={customerLogin}
setCustomerLogin={setCustomerLogin}
/>}
/>
</Switch>
</div>
);
}
请注意,我使用了一些不同的语法来路由Login
组件,你仍然会得到相同的结果,只是现在你可以将任何你想要的 props 传递给组件来呈现。您可以在此处阅读有关这种路由的更多信息。
然后,您可以Login
通过 props 在组件中访问它们:
const Login = ({setCustomerLogin, customerLogin}) => {
const handleChange = event => {
setCustomerLogin({
...customerLogin,
[event.target.name]: event.target.value
});
};
const handleSubmit = e => {
e.preventDefault();
axios
.post("/api/Authentication", customerLogin)
.then(function(response) {
setCustomerLogin(response.data);
console.log(response);
})
.catch(function(error) {
console.log(error);
});
};
推荐阅读
- linq - Join() 中的查询表达式问题
- reactjs - React & Webpack 4 - 延迟加载 - 无法生成块文件
- ios - UITableViewController 继承自 UIViewController
- java - spring boot中各种数据不匹配如何处理jackson反序列化错误
- javascript - 添加复选框以排除多项选择题的可能答案
- sql-server - 应用过滤器对季度数据求和
- c# - 在向系统添加新功能时,如何避免不断更改界面?
- c# - MvvmCross - 如何添加自定义模态转换
- php - 我想在 laravel 的选择选项菜单中显示整个国家列表
- linux - logrotate:即使我使用了 -f 选项,每日轮换也不起作用