简体   繁体   English

无效的挂钩调用。 如何通过反应 axios 来设置值?

[英]Invalid hook call. How to set a value with react axios get call?

I have this react component that has a simple form where, when you put a superhero name, it makes an axios get request to an API that responds successfully with json object with info of said hero. I have this react component that has a simple form where, when you put a superhero name, it makes an axios get request to an API that responds successfully with json object with info of said hero. That info is stored in the state and then mapped through to create a grid.该信息存储在 state 中,然后通过映射创建一个网格。 It used to work just fine as a class element so I started doing other parts of the app that have nothing to do with this part, but when i run the whole app again so check i get an hook call error in this component.它曾经作为 class 元素工作得很好,所以我开始做与这部分无关的应用程序的其他部分,但是当我再次运行整个应用程序时,请检查我在这个组件中得到一个钩子调用错误。

This is the seeker component, i did the class and the funcion version.这是搜索器组件,我做了 class 和功能版本。

import React, { useState } from "react";
import { Formik, Form, Field, ErrorMessage } from 'formik';
import axios from "axios";
require("babel-core/register");
require("babel-polyfill");
import grid from "../components/grid";


/* 
const Seeker = () => {
   const fetchData = (data) => {axios.get(`https://www.superheroapi.com/api.php/1589015884770221/search/${name}`)
       .then((response) => {
           localStorage.setItem("addHeroAction", true);
           let results = response.data.results;
           localStorage.setItem("matchedHeros", results);
       }).catch((error) => {
           console.log(error)
       })
   }

   let matchedHeros = localStorage.getItem("matchedHeros") ? localStorage.getItem("matchedHeros") : [];
   
   const gridRender = (response) =>{
       if(response.length && response != undefined){
           console.log(response)
           return( 
           <div className="grid__background">
           <div className="grid">
               <div className="grid__box grid__top grid__top--container"></div>
               <div className="grid__box grid__top grid__top--container"><h2>Name</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Intelligence</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Strenght</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Speed</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Durability</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Power</h2></div>
               <div className="grid__box grid__top grid__top--container"><h2>Combat</h2></div>
               <div className="grid__box grid__top grid__top--container"></div>
               {response.map(hero => grid(hero, hero.id))}
           </div>
           </div>)
       } else {
           return (<div></div>)
       }
   }

   return (
       <div>
           <h1>Find your next teammate!</h1>
               <Formik
               initialValues={{ name: ''}}
               validate={values => {
                   const errors = {};
                   if (!values.name) {
                       errors.name = 'Required';
                   } else if (
                       !/^[a-zA-Z]*$/.test(values.name)
                   ) {
                       errors.name = 'Invalid name';
                   }
                   return errors;
               }}
               onSubmit={(values) => {
                   console.log(fetchData(values.name));
               }}
               >
               {() => (
                   <Form>
                   <Field type="text" name="name" />
                   <ErrorMessage name="name" component="div" />
                   <button type="submit">
                       Submit
                   </button>
                   </Form>
               )}
               </Formik>
                   {gridRender(matchedHeros)}
       </div>
       )
   } */


   class Seeker extends React.Component{
   state = {
       matchedHeros : [],
       loadingData : true
   }
   constructor(){
       super();
       this.fetchData = this.fetchData.bind(this);
   }

   
   fetchData = async (name) => {
       if(this.state.loadingData){
           await axios.get(`https://www.superheroapi.com/api.php/1589015884770221/search/${name}`)
           .then((response) => {
               localStorage.setItem("addHeroAction", true);
               this.setState({matchedHeros : response.data.results, loadingData : false});
           }).catch((error) => {
               console.log(error)
           })
       }
  
       
   }     

   
   render(){
       return (
           <div>
               <h1>Find your next teammate!</h1>
                   <Formik
                   initialValues={{ name: ''}}
                   validate={values => {
                       const errors = {};
                       if (!values.name) {
                           errors.name = 'Required';
                       } else if (
                           !/^[a-zA-Z]*$/.test(values.name)
                       ) {
                           errors.name = 'Invalid name';
                       }
                       return errors;
                   }}
                   onSubmit={(values) => {
                       this.fetchData(values.name);
                   }}
                   >
                   {() => (
                       <Form>
                       <Field type="text" name="name" />
                       <ErrorMessage name="name" component="div" />
                       <button type="submit">
                           Submit
                       </button>
                       </Form>
                   )}
                   </Formik>
                   {console.log(this.state.matchedHeros)}
                   {this.state.matchedHeros.length ?  
                       (
                       <div className="grid__background">
                           <div className="grid">
                               <div className="grid__box grid__top grid__top--container"></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Name</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Intelligence</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Strenght</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Speed</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Durability</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Power</h2></div>
                               <div className="grid__box grid__top grid__top--container"><h2>Combat</h2></div>
                               <div className="grid__box grid__top grid__top--container"></div>
                           </div>
                       </div>
                       )
                       :
                       <div></div>
                   }
                   {this.state.matchedHeros.map(hero => grid(hero, hero.id))}
           </div>
           )
   }
} 


export default Seeker; 

It uses the formik library to verified the values and the it maps the info with a Grid component that works just fine on its own, so the problem is in this component.它使用 formik 库来验证值,并将信息映射到一个 Grid 组件,该组件本身就可以正常工作,所以问题出在这个组件上。 The axios call also sets a value in localStorage that i need to be set when the button is clicked. axios 调用还在 localStorage 中设置了一个值,我需要在单击按钮时设置该值。

The original was the class component but with it I have this error on the console.原来是 class 组件,但我在控制台上有这个错误。

"Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component." “未捕获的错误:无效的挂钩调用。挂钩只能在 function 组件的主体内部调用。”

Then i made the functional component version, which is commented in the code above, but with it i can't get the state updated with axios.然后我制作了功能组件版本,该版本在上面的代码中进行了注释,但使用它我无法使用 axios 更新 state。

When i look into someone else's examples they look like mine but I still get the hook call error, i already checked that i have up-to-date versions of react so that's not the problem.当我查看其他人的示例时,它们看起来像我的,但我仍然遇到钩子调用错误,我已经检查过我有最新版本的 react,所以这不是问题。 What am I doing wrong?我究竟做错了什么? or else, what suggestion can you guys give me to achieve the same result?否则,你们能给我什么建议来达到同样的结果?

If you want to get heroes when component is initially mounted:如果你想在组件初始挂载时获取英雄:

import React, { useState, useEffect } from "react";

async function getHeros(name) {
    return axios.get(
        `https://www.superheroapi.com/api.php/1589015884770221/search/${name}`
    );
}

const Seeker = () => {
    const [heros, setHeros] = useState([]);

    useEffect(() => {
        getHeros('someName').then((heros) => {
            console.log('heros: ', heros);
            setHeros(heros);
            localStorage.setItem("matchedHeros", heros);
        }, console.error);
    }, []);

    return (
        <div>
            {heros.map((hero, i) => (
                <span>{hero}</span>
            ))}
        </div>
    );
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 无效的钩子调用。 React.js - Invalid hook call. React.js 如何修复 React(TypeScript) 错误“无效的钩子调用。”? - How to fix React(TypeScrtipt) error “Invalid hook call.”? TypeScript React 无效的挂钩调用错误(“错误:无效的挂钩调用。”) - TypeScript React Invalid Hook Call Error ("Error: Invalid hook call.") 无效的钩子调用。 Hooks 只能在内部调用……如何解决这个问题,维护 React 类组件 - Invalid hook call. Hooks can only be called inside… how to fix this maintaining the react class component 未捕获的错误:无效的挂钩调用。 ReactJs - Uncaught Error: Invalid hook call. ReactJs 反应钩子错误:无效的钩子调用。 钩子只能在 function 组件的主体内部调用 - React hook Error: Invalid hook call. Hooks can only be called inside of the body of a function component 我如何通过此错误无效的挂钩调用。 钩子只能在 function 组件的主体内部调用。 我正在使用 React18 - How do i get pass this error Invalid hook call. Hooks can only be called inside of the body of a function component. i am using React18 反应无效的钩子调用,但如何有无效的钩子调用 - React Invalid hook call but how there is invalid hook call 反应 - 无效的钩子调用。 未捕获的错误:缩小的 React 错误 #321 - React - invalid hook call. Uncaught Error: Minified React error #321 反应:无效的挂钩调用。 挂钩只能在功能组件的主体内部调用 - React: Invalid hook call. Hooks can only be called inside of the body of a function component
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM