我正在尝试创建一个基本的 react
带钩子(Hook)的功能组件。
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 Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component.
如何检查是否 user
已设置为状态或未设置,并基于该渲染 Dashboard
组件 react-hooks
?
最佳答案
您没有从功能组件调用 Hook 。希望以下内容能解决您的疑虑。
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;
关于javascript - React Hooks - 根据状态有条件地渲染组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59994481/