Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - Variable inside UseEffect on React.js

I want to show the variable from API in variax

I use axios to access api for django rest-framework and then

put this in variax

But it still shows 2

I am famillier with Django but not django

Please give me some help.

import React, { Fragment, useEffect } from 'react';
import axios from 'axios';

const App = () => {


  let variax = 1;
  variax = 2;
  useEffect(() => {
    axios.get('http://localhost:8000/api/results/')
    .then(res=>{
      console.log(res.data);
      variax = res.data;
    })
    .catch(err=>{console.log(err);});
  }, []);
  return(
    <Fragment>
      {variax}
    </Fragment>
  );
}

export default App;

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

1 Answer

0 votes
by (71.8m points)

Since you are assigning variax in the render body of the component, it will always have the value 2. I suggest you store the value of variax in the state instead of declare a variable. Try this:

import React, { Fragment, useEffect, useState } from 'react';
import axios from 'axios';

const App = () => {
  const [variax, setVariax] = useState(1)

  useEffect(() => {
    axios.get('http://localhost:8000/api/results/')
      .then(res => {
        console.log(res.data);
        setVariax(res.data)
      })
      .catch(err => { console.log(err); });
  }, []);

  return (
    <Fragment>
      {variax}
    </Fragment>
  );
}

export default App;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...