亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用 React hooks 每 X 秒顯示一個不同的值

使用 React hooks 每 X 秒顯示一個不同的值

開心每一天1111 2023-03-03 18:56:25
所以基本上感謝 Mateo 的指點,我能夠使用這個腳本更新項目元數據:function alex_test_function() { // get existing oauth token var theAccessTkn = ScriptApp.getOAuthToken(); // get existing project metadata var response =  UrlFetchApp.fetch('https://compute.googleapis.com/compute/v1/projects/myProject', {   headers: {     Authorization: 'Bearer ' + theAccessTkn   } }); var data = JSON.parse(response.getContentText()); var metadata = data.commonInstanceMetadata fingerprint = metadata.fingerprint; new_metadata_items = metadata.items;// update metadata var timestamp = new Date().getTime() setMetaKey(new_metadata_items, Session.getActiveUser().getEmail().split("@")[0], timestamp) var formData = {  'fingerprint': fingerprint,  'items': new_metadata_items  }; var postresponse = UrlFetchApp.fetch("https://compute.googleapis.com/compute/v1/projects/myProject/setCommonInstanceMetadata", {  'method' : 'post',  'contentType': 'application/json',  'payload' : JSON.stringify(formData),  'headers': {    Authorization: 'Bearer ' + theAccessTkn   }  });}function setMetaKey(metadata, key, value){  // Function to add metadata or update if exists  for (var i = 0; i < metadata.length; i++) {    if (metadata[i].key === key) {      metadata[i].value = value;      return;    }  }  metadata.push({key:key, value:value});}一些陷阱,我們需要將 OAuth 范圍設置為 AppScript 清單{  "timeZone": "America/New_York",  "dependencies": {  },  "exceptionLogging": "STACKDRIVER",  "runtimeVersion": "V8",  "oauthScopes": [    "https://www.googleapis.com/auth/userinfo.email",     "https://www.googleapis.com/auth/compute",     "https://www.googleapis.com/auth/script.external_request"]}并且運行腳本的用戶需要具有編輯 GCP 項目中的項目元數據的權限。我沒有對范圍進行很多實驗,可以用更窄的范圍而不是https://www.googleapis.com/auth/compute來執行腳本我想顯示“Orange”2 秒,“Kiwi”或 1 秒,“Mango”3 秒。這是我的嘗試,它顯示靜止的“橙色:2000”,而我希望它根據指定的秒數翻轉。我錯過了什么?
查看完整描述

3 回答

?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

讓您的組件在索引更改時由其狀態驅動,它會觸發更新 currentFruit 狀態的 useEffect 掛鉤,currentFruit 更改會觸發另一個更新索引的 useEffect 等等,然后只需使用 like setTimeout:


const IntervalExample = () => {

    const fruits = [

        {id: 1, name: "Orange", duration: 2000},

        {id: 2, name: "Kiwi", duration: 1000},

        {id: 3, name: "Mango", duration: 3000},

    ]


    const [index, setIndex] = useState(0);

    const [currentFruit, setCurrentFruit] = useState(fruits[index]);


   

    

    useEffect(() => {

        setCurrentFruit(fruits[index])

    }, [index])


    useEffect(() => {

        const interval = setTimeout(() => {

            setIndex(index === fruits.length - 1 ? 0 : index + 1)       

        }, currentFruit.duration);

    }, [currentFruit])


    return (

        <div className="App">

            <header className="App-header">

                {currentFruit.name}: {currentFruit.duration}

            </header>

        </div>

    );

};


查看完整回答
反對 回復 2023-03-03
?
慕虎7371278

TA貢獻1802條經驗 獲得超4個贊

UseEffect 只被調用一次。因此,Const interval將為時間間隔的函數調用初始化一個閉包。它永遠不會改變。關閉中的索引將始終為 0。


這是我的解決方案,只需使用一種狀態作為索引:


const IntervalExample = () => {

    const fruits = [

        {id: 1, name: "Orange", duration: 2000},

        {id: 2, name: "Kiwi", duration: 1000},

        {id: 3, name: "Mango", duration: 3000},

    ]


    const [index, setIndex] = useState(0);


    //because fruit depend on index. Dont need a separate state

    const currentFruit = fruits[index];


    const handleIndex = () => {

        setIndex(index === fruits.length - 1 ? 0 : index + 1)

    }


    useEffect(() => {

        //after render current fruit. We new timeout to set next fruit.

        setTimeout(handleIndex, currentFruit.duration);

    }, [index]);


    return (

        <div className="App">

            <header className="App-header">

                {currentFruit.name}: {currentFruit.duration}

            </header>

        </div>

    );

};


查看完整回答
反對 回復 2023-03-03
?
慕的地8271018

TA貢獻1796條經驗 獲得超4個贊

如果你想為每個水果使用不同的超時,那setTimeout將是更好的方法。


由于在初始值setInterval被調用時會被設置為改變顯示水果信息的時間間隔。useEffect


您的代碼中的問題是在更新index狀態時未正確更新。


為了解決這個問題而不是直接更新值,我使用更新后的狀態值,如下所示


setIndex((index) => (index === fruits.length - 1 ? 0 : index + 1))

const { useState, useEffect } = React;


const fruits = [

  { id: 1, name: "Orange", duration: 2000 },

  { id: 2, name: "Kiwi", duration: 1000 },

  { id: 3, name: "Mango", duration: 3000 }

];


const IntervalExample = () => {

  const [index, setIndex] = useState(0);

  const [currentFruit, setCurrentFruit] = useState(fruits[0]);


  useEffect(() => {

    const interval = setInterval(() => {

      setIndex((index) => (index === fruits.length - 1 ? 0 : index + 1));

    }, fruits[index].duration);

    return () => clearInterval(interval);

  }, []);


  useEffect(() => {

    setCurrentFruit(fruits[index]);

  }, [index]);


  return (

    <div className="App">

      <header className="App-header">

        {currentFruit.name}: {currentFruit.duration}

      </header>

    </div>

  );

};



ReactDOM.render(

       <IntervalExample />,

       document.getElementById("root")

     );

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>


<div id="root"></div>


查看完整回答
反對 回復 2023-03-03
  • 3 回答
  • 0 關注
  • 193 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號