Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

javascript - Infinte Loop in React while using navigator.geolocation.watchPosition

So I am trying to get the position of the user and store it in a React.State. I have a settings page where the user can set settings.positionAllowed to either true or false by pressing a button, false is the default value. Until pressing the button, everything works fine. But as soon as the user sets the setting to true and goes back to home page, an endless loop is created and the app crashes after some time. I first thought that the reason for this is that an instance of navigator.geolovation.watchPosition is created on every re-rendering of the component. But also the effect hook did not solve the problem.

Here is my code:

navigator.geolocation ? let posObj = {positionAllowed: false} : let posObj = {positionAllowed: true};

const [settings, setSettings] = useState(posObj);
useEffect(() => {
    if(settings.positionAllowed&&navigator.geolocation){
        let geolocation = navigator.geolocation.watchPosition((rawPosition)=>{
            let positionData = {
                positionAvailable: true,
                    data: rawPosition
                }
                if(positionData!=position){
                    setPosition(positionData);
                }
            },(err)=>{
                console.log(err);
            },{
                enableHighAccuracy: true,
                maximumAge: 10000
            });
        }
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to pass [] as the second parameter of useEffect. Then, it will work like componentDidMount() in the class component. Unless, it will be called every time the state's updated, and will occur infinite loops.

navigator.geolocation ? let posObj = {positionAllowed: false} : let posObj = {positionAllowed: true};

const [settings, setSettings] = useState(posObj);
useEffect(() => {
    if(settings.positionAllowed&&navigator.geolocation){
        let geolocation = navigator.geolocation.watchPosition((rawPosition)=>{
            let positionData = {
                positionAvailable: true,
                    data: rawPosition
                }
                if(positionData!=position){
                    setPosition(positionData);
                }
            },(err)=>{
                console.log(err);
            },{
                enableHighAccuracy: true,
                maximumAge: 10000
            });
        }
    }
}, []);  // <---------------------------------

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...