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
364 views
in Technique[技术] by (71.8m points)

react useState useEffect的问题

function CreateForm (props) {
  const [industry, setIndustry] = useState([]) // 行业
  
  useEffect(() => {
    const getIndData = async () => {
      let res = await getIndustry();
      setIndustry(x => {
        x = res.map(item => {
          return {
            id: item.id, 
            label: item.name,
            pcUrl: item.pcUrl,
            wapUrl: item.wapUrl
          }
        })
        console.log(x, 8)
      })
      console.log('industry', industry,9)
    }
    console.log('industry', industry, 7)
    getIndData()
  }, [])
  console.log('industry', industry, 6)

  return (
    <div>
      {industry.map(item => (
        <p key={item.id}>{item.label}</p>
      ))}
    </div>
  )
}

export default Form.create()(CreateForm);

为什么console.log(x, 8)已经把值赋进去了.
console[9]/ [7] / [6] 都取不到值?
哪里错了吗


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

1 Answer

0 votes
by (71.8m points)

因为 setIndustry 是异步的。


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

...