Javascript 无效的钩子调用。钩子只能在内部调用。。。如何修复此问题并维护react类组件
我是react初学者,所以我知道的不多,我尝试调用一个函数,其中JWT令牌从本地存储获取,并与从后端获取的进行比较,方法是发送一个Axios请求,这样如果我得到200响应,这意味着我可以将其重定向到另一个页面,虽然这是一个错误,但我可以请求用户登录。(请注意,这不是一个专业项目,但我非常需要你们的帮助,伙计们) 我面临的问题是,我在购物车中设置OnClick按钮的方式是否正确? 如何修复作为类维护时出现的React钩子错误? 未处理的拒绝(错误):钩子调用无效。钩子只能在函数组件的主体内部调用Javascript 无效的钩子调用。钩子只能在内部调用。。。如何修复此问题并维护react类组件,javascript,reactjs,Javascript,Reactjs,我是react初学者,所以我知道的不多,我尝试调用一个函数,其中JWT令牌从本地存储获取,并与从后端获取的进行比较,方法是发送一个Axios请求,这样如果我得到200响应,这意味着我可以将其重定向到另一个页面,虽然这是一个错误,但我可以请求用户登录。(请注意,这不是一个专业项目,但我非常需要你们的帮助,伙计们) 我面临的问题是,我在购物车中设置OnClick按钮的方式是否正确? 如何修复作为类维护时出现的React钩子错误? 未处理的拒绝(错误):钩子调用无效。钩子只能在函数组件的主体内部调用
import React, { Component } from "react";
import { Link, useHistory } from "react-router-dom";
import axios from "axios";
export default class NavBar extends Component {
// eslint-disable-next-line
constructor(props) {
super(props);
}
async tokenizedCartRedirect() {
var history = useHistory();
var token = localStorage.getItem("currentToken");
if (token != "") {
const config = {
headers: { "Content-Type": "application/json", "x-auth-token": token },
mode: "cors",
};
const body = JSON.stringify(token);
const res = axios
.post("http://localhost:5000/auth", body, config)
.then((res) => {
history.push("/cart");
})
.catch((err) => {
history.push("/login");
});
} else {
history.push("/login");
}
}
render() {
//const element = (<div>Text from Element</div>)
return (
<header id="site-header" className="site-header__v7">
<div className="topbar d-none d-md-block bg-punch-light">
<div className="container">
<div className="topbar__nav d-lg-flex justify-content-between align-items-center font-size-2">
<ul className="topbar__nav--left nav ml-lg-n3 justify-content-center">
<li className="nav-item">
<a href="#" className="nav-link text-dark">
<i className="font-size-3 glph-icon flaticon-question mr-2" />
Can we help you?
</a>
</li>
<li className="nav-item">
<a href="#" className="nav-link text-dark">
<i className="font-size-3 glph-icon flaticon-phone mr-2" />
+1246-345-0695
</a>
</li>
</ul>
</div>
</div>
</div>
<div className="masthead">
<div className="bg-white border-bottom">
<div className="container pt-3 pb-2 pt-lg-5 pb-lg-5">
<div className="d-flex align-items-center position-relative flex-wrap">
<div className="site-branding pr-md-11 mx-auto mx-md-0">
<Link to="/" className="d-block mb-1">
<img
src={require("../../assets/img/logo.png")}
className="img-fluid"
alt="image-description"
width="330px"
/>
</Link>
</div>
<div className="site-search ml-xl-0 ml-md-auto w-r-100 flex-grow-1 mr-md-5 py-2 py-md-0">
<form className="form-inline my-2 my-xl-0">
<div className="input-group w-100">
<input
type="text"
className="form-control border-right-0 px-3"
placeholder="Search for comics by keyword"
aria-label="Amount (to the nearest dollar)"
/>
<div className="input-group-append border-left">
<button
className="btn btn-dark px-3 rounded-0 py-2"
type="submit"
>
<i className="mx-1 glph-icon flaticon-loupe"></i>
</button>
</div>
</div>
</form>
</div>
<ul className="nav align-self-center d-none d-md-flex">
<li className="nav-item">
<a href="#" className="nav-link text-dark">
<i className="glph-icon flaticon-heart font-size-4"></i>
</a>
</li>
<li className="nav-item">
<Link
to="/login"
id="sidebarNavToggler"
role="button"
className="nav-link text-dark"
aria-controls="sidebarContent"
aria-haspopup="true"
aria-expanded="false"
data-unfold-event="click"
data-unfold-hide-on-scroll="false"
data-unfold-target="#sidebarContent"
data-unfold-type="css-animation"
data-unfold-overlay='{
"className": "u-sidebar-bg-overlay",
"background": "rgba(0, 0, 0, .7)",
"animationSpeed": 500
}'
data-unfold-animation-in="fadeInRight"
data-unfold-animation-out="fadeOutRight"
data-unfold-duration="500"
>
<i className="glph-icon flaticon-user font-size-4"></i>
</Link>
</li>
<li className="nav-item">
<dev
id="sidebarNavToggler1"
role="button"
className="nav-link pr-0 text-dark position-relative"
aria-controls="sidebarContent1"
aria-haspopup="true"
aria-expanded="false"
data-unfold-event="click"
data-unfold-hide-on-scroll="false"
data-unfold-target="#sidebarContent1"
data-unfold-type="css-animation"
data-unfold-overlay='{
"className": "u-sidebar-bg-overlay",
"background": "rgba(0, 0, 0, .7)",
"animationSpeed": 500
}'
data-unfold-animation-in="fadeInRight"
data-unfold-animation-out="fadeOutRight"
data-unfold-duration="500"
>
<i
className="glph-icon flaticon-icon-126515 font-size-4"
onClick={this.tokenizedCartRedirect()}
></i>
</dev>
</li>
</ul>
</div>
</div>
</div>
<div className="border-bottom py-3 py-md-0">
<div className="container">
<div className="d-md-flex position-relative">
<div className="site-navigation mr-auto d-none d-xl-block">
<ul className="nav">
<li className="nav-item">
<Link
to="/"
className="nav-link link-black-100 mx-2 px-0 py-3 font-weight-medium active border-bottom border-primary border-width-2"
>
Home
</Link>
</li>
<li className="nav-item">
<Link
to="/products"
className="nav-link link-black-100 mx-2 px-0 py-3 font-weight-medium active border-bottom border-primary border-width-2"
>
Browse Comics
</Link>
</li>
</ul>
</div>
<div className="d-none d-md-block ml-md-auto secondary-navigation ">
<ul className="nav">
<li className="nav-item">
<a
href="#"
className="nav-link link-black-100 mx-2 px-0 py-3 font-weight-medium"
>
Subscription Pricing
</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</header>
);
}
}
import React,{Component}来自“React”;
从“react router dom”导入{Link,useHistory};
从“axios”导入axios;
导出默认类导航栏扩展组件{
//eslint禁用下一行
建造师(道具){
超级(道具);
}
异步令牌化CartRedirect(){
var history=useHistory();
var token=localStorage.getItem(“currentToken”);
如果(令牌!=“”){
常量配置={
标题:{“内容类型”:“应用程序/json”,“x-auth-token”:token},
模式:“cors”,
};
const body=JSON.stringify(令牌);
常数res=axios
.post(“http://localhost:5000/auth,主体,配置)
。然后((res)=>{
历史。推送(“/购物车”);
})
.catch((错误)=>{
history.push(“/login”);
});
}否则{
history.push(“/login”);
}
}
render(){
//常量元素=(元素中的文本)
返回(
-
-
-
-
-
-
家
-
浏览漫画
-
);
}
}
不能在类组件中使用挂钩
钩子useHistory
永远不会在类中工作,您需要将其移到类外的包装功能组件或将此组件转换为功能组件
对于一个好的指南,你应该看看这个,它显示了如何一步一步地转换它
如何使用挂钩的示例
constmycomp=(道具)=>{
const history=useHistory();
const tokenizedCartRedirect=async(history)=>{/*code*/};
返回(
tokenizedCartRedirect(历史)}/>
)
}
函数组件是在React中创建组件的不同方法,而不是类
如以下示例所示:
import React,{useState}来自“React”;
函数示例(){
//声明一个新的状态变量,我们称之为“count”
const[count,setCount]=useState(0);
返回(
您单击了{count}次
设置计数(计数+1)}>
点击我
);
}
您可以在这里有一个好主意:useHistory是生成错误的钩子这是否回答了您的问题?我试着这么做,但是在函数“tokenizedCartRedirect”中调用了**React-Hook“useHistory”,该函数既不是React-function组件,也不是自定义React-Hook函数**@NataliaKolisnyk我添加了一个示例,向您展示如何使用并将历史传递给点击。
const MyComp = (props) => {
const history = useHistory();
const tokenizedCartRedirect = async (history) => {/* code */};
return (
<div>
<SomeComponent onClick={() => tokenizedCartRedirect(history)} />
</ div>
)
}