реагировать на нагрузку компонента 5 раз «не определено», затем он находит внутренний html div - PullRequest
0 голосов
/ 02 мая 2020

выделенный текст

import React, { useState, useEffect,useRef } from "react";
import Axios from "./axios.js";


//ADblockerdetection
export  function Adblockerdetection() {
    const [firstname, setfirstname] = useState('');

    const [adblock, adblocdetected] = useState(false);

 Axios.get("/user").then((result) => {
       setfirstname(
       result.data.firstname
           );
         }); 

    useEffect(() => {
        return Adblockerdetection();
    });
  
 
    function Adblockerdetection() {
        const head = document.getElementsByTagName("head")[0];

        const noadblock = () => {
            adblocdetected(false);
        };

        const adblocker = () => {
            adblocdetected(true);
        };

        const script = document.createElement("script");
        script.id = "adblock-detection";
        script.type = "text/javascript";
        script.src = "./public/gpt.js";
        script.onload = noadblock;
        script.onerror = adblocker;
        head.appendChild(script);

        //this.adblocdetected() = this.adblocdetected().bind(this);
    }
    return (
        <div>
           
            <div className="AdblockerMessage">
                {adblock ? (<div className="modal1">
                    <div id="adblock_message" >
                        <h2>HELLO {firstname}</h2>
                        <p>it looks like you are using an Adblocker. <br/>Please disable
                        the adblocker for this page!</p>
                        <button
                            onClick={() => {
                                Adblockerdetection( window.location.reload(true));
                            }}
                        >
                          
                        try to proof of Adblocker
                        </button>
                    </div>
                    </div>
                ) : (
                   null
                )}
           
            </div>
        </div>
    );
}


export default function Adinjection(props) {
    const { adtype, zoneid, id, name } = props;
        var therealURL =
        "https://marcpassenheim.net/AdServerTest/www/delivery/afr.php?";
    var theRandom = Math.floor(Math.random() * 1000000 + 1);
    var urlparam = {
        zoneid: zoneid,
        cb: theRandom,
    };
    var theURL = Object.keys(urlparam)
        .map((key) => key + "=" + urlparam[key])
        .join("&");
    //the adurl
    var construUrl = therealURL + theURL;
//------USEstat--------------------------------------------


//----------------------------------------

    const ads = {
        bigsky: {
            id: id,
            name: name,
            src: construUrl,
            width: "160" + "px",
            height: "600" + "px",
        },
        sky: {
            id: id,
            name: name,
            src: construUrl,
            width: "120" + "px",
            height: "600" + "px",
        },

        billboard: {
            id: id,
            name: name,
            src: construUrl,
            width: "800" + "px",
            height: "250" + "px",
        },
        bigbillboard: {
            id: id,
            name: name,
            src: construUrl,
            width: "970" + "px",
            height: "250" + "px",
        },
        mediumrectangle: {
            id: id,
            name: name,
            src: construUrl,
            width: "300" + "px",
            height: "250" + "px",
        },
        hpa: {
            id: id,
            name: name,
            src: construUrl,
            width: "300" + "px",
            height: "600" + "px",
        },
    };
    //Component where the ADTYPE prop is overgiven
    const currentAd = ads[adtype];

 //----------------HIDETheSpots-------------------------
const [visible, setAdSpotvisible] = useState(false);

 useEffect( () => {
  
      return setAdSpotvisible(true);
 }, []);

//setthecomponent to display:none when its not loaded
const divStyleNone = {
 display: "none !important",
 height:0+'px !important',
 width:0+'px !important'
};
const divstyleBlock = {
 display: "block",
 background: "yellow",
 height:'auto',
 width:'auto'
 
};



const [iframe,stateiframe] =useState(<iframe/>)
const containerToProof = useRef()

const isEmpty = containerToProof.current;
if(isEmpty==='undefined'){
       console.log('allo')
}
useEffect(()=>{
    console.log('saysomething',isEmpty)   
    },[<iframe/>]);


    return (
        <div>
           <div  ref={containerToProof}  >

               {visible ? (<div style={divstyleBlock}>
                            <iframe
                                id={currentAd.id}
                                name={currentAd.name}
                                src={currentAd.src}
                                frameBorder="no"
                                scrolling="no"
                                width={currentAd.width}
                                height={currentAd.height}
                                allow="autoplay"
                               
                                
                            />
                        </div>):( <div style={divStyleNone}> </div>)
              
              
              
               }
        </div>
        </div>
    );







    
}

Привет, я пытаюсь доказать ответ рекламодателя. Чтобы проверить, какой тип ответа он использует, используйте useRef () и ссылку на div, где будет создан iframe, и отправьте запрос get на сервер объявлений https://i.stack.imgur.com/3kvMo.png

объект выглядит следующим образом:

https://i.stack.imgur.com/fe3aL.png

каждый раз, когда я refre sh страница, на которой выражение console.log 'sayomething' дает мне 5 раз неопределенное значение, а затем находит divs. https://i.stack.imgur.com/2V5bX.png

5adinjection.js:171 saysomething undefined
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​
adinjection.js:171 saysomething <div>​…​</div>​


Проблема в том, что мне нужно внутреннее значение HTML, чтобы немедленно работать с сохраненным значением в противном случае, когда я пытаюсь go включить в операторе if или что-то другое, консоль говорит: «Не могу найти ценность неопределенного бла-бла…». Я что-то пропустил, я застрял здесь на час и мне нужна помощь.

1 Ответ

0 голосов
/ 02 мая 2020

Кажется, вы должны запускать Adblockerdetection() только после первого монтирования. Для этого вам нужно передать пустой массив в зависимость useEffect. Также asyn c функции должны быть внутри useEffect.

    useEffect(() => {
       Axios.get("/user").then(result => {
          setfirstname(result.data.firstname);
       });
       return Adblockerdetection();
     }, []);

Также вы получаете undefined, потому что значение containerToProof.current присваивается только один раз переменной isEmpty. Поэтому вместо console.log('saysomething',isEmpty) измените на console.log('saysomething',containerToProof.current) внутри useEffect.

useEffect(()=>{
    console.log('saysomething',containerToProof.current)   
 },[<iframe/>]);

Чтобы проверить, загружен ли iframe

<div ref={containerToProof}>
          {visible ? (
            <div style={divstyleBlock}>
              <iframe
                id={currentAd.id}
                name={currentAd.name}
                src={currentAd.src}
                frameBorder="no"
                scrolling="no"
                width={currentAd.width}
                height={currentAd.height}
                allow="autoplay"
                onLoad={() => {
                  // iframe is loaded now and here you can call the function
                }}
              />
            </div>
          ) : (
            <div style={divStyleNone}> </div>
          )}
        </div>
...