简体   繁体   中英

How to use a value changed by useEffect?

So I have my code like this:

var problems = ['a','b','c'];
  var allProblemStatus;
  var selectProblemStatus = "";

  useEffect(() => {
    let getProblemStatus = async() => {
      let response = await fetch('http://127.0.0.1:8000/api/problem-status/');
      allProblemStatus = await response.json();
      selectProblemStatus = allProblemStatus['problem_status'];
    }
    getProblemStatus();
  }, []);

return (
    <div>
    {problems.map((problem, index) => (
        <Grid item xs={200} md={100} lg={5}>
          <Problem key={index} problem={problem} a={selectProblemStatus} />
        </Grid>
      
      ))}
    </div>
  );

selectProblemStatus is being changed in useEffect but how do I actually use it to pass it to the Problem component as a prop, also is there a way to console.log the changed selectProblemStatus

You can use useState() hook for your variables, and then in useEffect update them. Here is link how to use useState https://uk.reactjs.org/docs/hooks-state.html

it is clear that you are unfamiliar with useState hook in react. your approach should be look like this:

import { useState } from 'react'

const YourComponent = (props) => {
  const [problems, setProblems] = useState([])
  
  const getProblemStatus = async () => { ... }

  useEffect(() => {
    getProblemStatus()
  }, [])

  return (
    <div>
    {problems.map((problem, index) => (
        <Grid key={index} item xs={200} md={100} lg={5}>
          <Problem problem={problem} a={selectProblemStatus} />
        </Grid>
      ))}
    </div>
  )
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM