React Hooks - 根据状态有条件地渲染组件



我正在尝试创建一个带有钩子的基本react功能组件。

import React, { useState, useEffect } from 'react';
import Header from 'test-header';
import Dashboard from 'test-dashboard';
import { api } from '../api';
function storeUser(user) {
if (user) {
localStorage.user = JSON.stringify(user);
} else {
delete localStorage.user;
}
}
async function login() {
const [error, setError] = useState([]);
const [user, setUser] = useState([]);
try {
const user = await api({
endpoint: 'identity/login',
method: 'POST',
json: {
email: 'test@abc.com',
password: '12345'
}
});
setUser(user);
storeUser(user);
} catch (err) {
setError(err);
}
}
function Container() {
return (
<div>
<Header />
<input type="submit" value="Login" onClick={login}></input>
{/* if user sets in state then render <Dashboard /> else render error message  */}
</div>
);
}
export default Container;

在这里,test-header作为包发布的组件npm工作正常。当我单击Login按钮时,我收到此错误:

react-dom.development.js?61bb:16178 未捕获(承诺(错误: 无效的挂钩调用。钩子只能在主体内部调用 函数组件。

如何检查user是否已设置为状态,并基于该渲染Dashboard组件react-hooks

你不是从功能组件调用钩子。我希望以下内容能解决您的问题。

import React, {useState, useEffect} from 'react';
import Header from 'test-header';
import Dashboard from 'test-dashboard';
import {api} from '../api';
const Container = props => {
const [error, setError] = useState([]);
const [user, setUser] = useState([]);
function storeUser(user) {
if (user) {
localStorage.user = JSON.stringify(user);
} else {
delete localStorage.user;
}
}
async function login() {
try {
const user = await api({
endpoint: 'identity/login',
method: 'POST',
json: {
email: 'test@abc.com',
password: '12345',
},
});
// call setUser only if credentials are correct
if (validUser) {
setUser(user);
storeUser(user);
}
} catch (err) {
setError(err);
}
}
return (
<div>
<Header />
<input type="submit" value="Login" onClick={login}></input>
{user.length > 0 ? <Dashboard /> : error.length > 0 ? <Error /> : null}
</div>
);
};
export default Container;

将状态移出login。将钩子移到另一个钩子中。在功能组件中调用该钩子:

function useUser() {
const [error, setError] = useState([]);
const [user, setUser] = useState([]);
async function login() {
try {
const user = await api({   endpoint: 'identity/login', method: 'POST', json: { email: 'test@abc.com',  password: '12345'  }   });
setUser(user);
storeUser(user);
} catch (err) { setError(err);  }
}
return { user, error, login };
}

function Container() {
const { user, error, login } = useUser();
//...
}

相关内容

  • 没有找到相关文章

最新更新