Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 功能组件中的事件处理程序以及React中的挂钩_Javascript_Reactjs - Fatal编程技术网

Javascript 功能组件中的事件处理程序以及React中的挂钩

Javascript 功能组件中的事件处理程序以及React中的挂钩,javascript,reactjs,Javascript,Reactjs,我试图理解功能组件和挂钩。有一个组件可以从API下载引用数组,并且应该随机选择一个并将其作为道具发送给子组件“Quote” import React,{useState,useffect}来自“React”; 从“/Quote.js”导入报价; 函数App(){ const[quotes,setQuotes]=useState(); const[randomQuote,setRandomQuote]=useState(); useffect(()=>{ 取回(“https://type.fit/

我试图理解功能组件和挂钩。有一个组件可以从API下载引用数组,并且应该随机选择一个并将其作为道具发送给子组件“Quote”

import React,{useState,useffect}来自“React”;
从“/Quote.js”导入报价;
函数App(){
const[quotes,setQuotes]=useState();
const[randomQuote,setRandomQuote]=useState();
useffect(()=>{
取回(“https://type.fit/api/quotes那么(
response=>response.json())。然后(
数据=>{setQuotes(数据);
newRandomQuote()}
)},
[])
常量newRandomQuote=()=>{
var randomQuote=quotes[Math.floor(Math.random()*1643)];//它是由1643个引号组成的数组
setRandomQuote(randomQuote);
}
返回(
{quotes!=null&}
);
}
导出默认应用程序;
但我的newRandomQuote函数似乎不起作用,我的randomQuote状态未定义,我不理解它,因为我似乎可以从newRandomQuote外部访问quotes状态,但它从内部未定义。 如果我在组件中的某处添加console.log(引号),如下所示:

 const newRandomQuote=()=>{
  var randomQuote=quotes[Math.floor(Math.random() * 1643)];
  setRandomQuote(randomQuote);
  }

  console.log(quotes);

  return (
    <div>
     {quotes!=null&&<Quote quote={randomQuote}/>}
    </div>
  );
const newRandomQuote=()=>{
var randomQuote=quotes[Math.floor(Math.random()*1643)];
setRandomQuote(randomQuote);
}
console.log(引号);
返回(
{quotes!=null&}
);

它工作并向我显示数组,所以我不明白。

声明
newRandomQuote
上面的方法
useffect
,我认为应该工作。

声明
newRandomQuote
上面的方法
useffect
,我认为应该工作。

创建一个
useffect
quotes
状态反应

代码中的
未定义
是因为
引号
仍然是
未定义
时调用了
newRandomQuote
。它的值将仅在下一次更新或函数调用中更新。这就是为什么您需要创建一个新的
useffect
来跟踪
quotes
,并设置
randomQuote

import React, {useState, useEffect} from 'react';
import Quote from './Quote.js';

function App() {
 const[quotes, setQuotes]=useState();
 const[randomQuote, setRandomQuote]=useState();

 useEffect(()=>{
   fetch("https://type.fit/api/quotes")
     .then(response => response.json())
     .then(
       data => {
        setQuotes(data);
       }
     )},
 [])

 useEffect(() => {
   if (quotes) {
     const randomQuote = quotes[Math.floor(Math.random() * 1643)];  // it's array of 1643 quotes
     setRandomQuote(randomQuote);
   }
 }, [quotes])


 return (
   <div>
    {
      // Check against randomQuote instead of quotes
      // because, in the 2nd call, randomQuote will be undefined
      // while quotes will have response data
      // and also that's the value you need here
      randomQuote !== null && 
        <Quote quote={randomQuote}/>
    }
   </div>
 );
}

export default App;

import React,{useState,useffect}来自“React”;
从“/Quote.js”导入报价;
函数App(){
const[quotes,setQuotes]=useState();
const[randomQuote,setRandomQuote]=useState();
useffect(()=>{
取回(“https://type.fit/api/quotes")
.then(response=>response.json())
.那么(
数据=>{
setQuotes(数据);
}
)},
[])
useffect(()=>{
如果(引用){
const randomQuote=quotes[Math.floor(Math.random()*1643)];//它是由1643个引号组成的数组
setRandomQuote(randomQuote);
}
},[引用])
返回(
{
//对照随机引号而不是引号进行检查
//因为,在第二次调用中,randomQuote将是未定义的
//而引号将包含响应数据
//这也是你在这里需要的价值
randomQuote!==null&&
}
);
}
导出默认应用程序;

创建一个
useffect
引号
状态进行反应

代码中的
未定义
是因为
引号
仍然是
未定义
时调用了
newRandomQuote
。它的值将仅在下一次更新或函数调用中更新。这就是为什么您需要创建一个新的
useffect
来跟踪
quotes
,并设置
randomQuote

import React, {useState, useEffect} from 'react';
import Quote from './Quote.js';

function App() {
 const[quotes, setQuotes]=useState();
 const[randomQuote, setRandomQuote]=useState();

 useEffect(()=>{
   fetch("https://type.fit/api/quotes")
     .then(response => response.json())
     .then(
       data => {
        setQuotes(data);
       }
     )},
 [])

 useEffect(() => {
   if (quotes) {
     const randomQuote = quotes[Math.floor(Math.random() * 1643)];  // it's array of 1643 quotes
     setRandomQuote(randomQuote);
   }
 }, [quotes])


 return (
   <div>
    {
      // Check against randomQuote instead of quotes
      // because, in the 2nd call, randomQuote will be undefined
      // while quotes will have response data
      // and also that's the value you need here
      randomQuote !== null && 
        <Quote quote={randomQuote}/>
    }
   </div>
 );
}

export default App;

import React,{useState,useffect}来自“React”;
从“/Quote.js”导入报价;
函数App(){
const[quotes,setQuotes]=useState();
const[randomQuote,setRandomQuote]=useState();
useffect(()=>{
取回(“https://type.fit/api/quotes")
.then(response=>response.json())
.那么(
数据=>{
setQuotes(数据);
}
)},
[])
useffect(()=>{
如果(引用){
const randomQuote=quotes[Math.floor(Math.random()*1643)];//它是由1643个引号组成的数组
setRandomQuote(randomQuote);
}
},[引用])
返回(
{
//对照随机引号而不是引号进行检查
//因为,在第二次调用中,randomQuote将是未定义的
//而引号将包含响应数据
//这也是你在这里需要的价值
randomQuote!==null&&
}
);
}
导出默认应用程序;

const/let
变量未被提升,因此在声明之前不能使用它

提升是一种JavaScript机制,其中变量和函数声明在代码执行之前移动到其作用域的顶部。不可避免地,这意味着无论函数和变量声明在哪里,它们都会移动到其作用域的顶部,而不管其作用域是全局的还是局部的

如果
函数表达式
,则可以使用普通的
函数
。函数可以在定义之前使用<代码>函数
在JavaScript中提升

在组件装载和第一次执行
useffect
时,
newRandomQuote
函数将具有初始状态,因为状态更新是
async

您需要在
componentDidUpdate
lifecycle方法中调用
newRandomQuote()
。这等于带有依赖项数组的
useffect

始终使用预期的数据类型初始化状态

试试这个

import React, { useState, useEffect } from 'react';
import Quote from './Quote.js';

function App() {
    const [quotes, setQuotes] = useState([]);
    const [randomQuote, setRandomQuote] = useState([]);

    useEffect(() => {
        fetchData();
    }, []);

    useEffect(() => {
        newRandomQuote();
    }, [quotes]);

    async function fetchData() {
        try{
            let response = await fetch("https://type.fit/api/quotes");
            let data = await response.json();
            setQuotes(data);
        } catch(error) {
            console.log(error);
        }

    }
    function newRandomQuote() {
        if (quotes.length > 0) {
            let randomQuote = quotes[Math.floor(Math.random() * 1643)];
            setRandomQuote(randomQuote);
        }
    }

    return (
        <div>
            {quotes != null && <Quote quote={randomQuote} />}
        </div>
    );
}
export default App;

import React,{useState,useffect}来自“React”;
从“/Quote.js”导入报价;
函数App(){
const[quotes,setQuotes]=useState([]);
const[randomQuote,setRandomQuote]=useState([]);
useffect(()=>{
fetchData();
}, []);
useffect(()=>{
newRandomQuote();
},[引述];
异步函数fetchData(){
试一试{
let response=等待获取(“https://type.fit/api/quotes");
让data=wait response.json();
setQuotes(数据);
}捕获(错误){
console.log(错误);
}
}
函数newRandomQuote(){
如果(quotes.length>0