如何使用 useEffect 改变的值?

How to use a value changed by useEffect?

所以我的代码是这样的:

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 正在 useEffect 中更改,但我如何实际使用它来将它作为道具传递给 Problem 组件,还有没有办法 console.log 更改selectProblemStatus

您可以使用 useState() 挂钩您的变量,然后在 useEffect 中更新它们。这里是 link 如何使用 useState https://uk.reactjs.org/docs/hooks-state.html

很明显你不熟悉useState hook in react。 你的方法应该是这样的:

import { useState } from 'react'

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

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

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