React中动态设置状态无效
P粉366946380
P粉366946380 2023-09-08 17:35:50
0
1
413

我正在尝试动态设置一个数组,并使用useState hook进行渲染。但似乎数组没有设置。以下是我的代码:

import React, { useState, useEffect } from "react";

export default ({ item }) => {
    const [attachments, setAttachments] = useState([]);
    const setAttachmentValues = function(response){
        setAttachments(response.data);
        
    }
    const fetchMedia = async ()=> {
        setAttachments([]);           
        await apiCall().then((response) => {                
            setAttachmentValues(response);                
        });
    }
    
    useEffect(() => {
        fetchMedia();
    }, []);
    return (
        <>
           <div className="w-full">
                {(attachments.map((ele) => {
                      <div>{ele}</div>
                )} 
        </>
    )
}

apiCall()将返回一个对象数组。

在某些情况下,以这种方式设置状态是有效的。这里的实际问题是什么?

P粉366946380
P粉366946380

全部回复(1)
P粉868586032

这样你就可以渲染数据了

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

export default ({ item }) => {
  const [attachments, setAttachments] = useState([]);

  useEffect(() => {
    
    fetch('https://jsonplaceholder.typicode.com/users')
      .then((response) => response.json())
      .then((response) => {
        setAttachments(response);
        console.log(response);
      });
  }, []);
  return (
    <>
       <div>
        {attachments.map(item => <div key={item.username}> {item.username} </div> )}
      </div>
    </>
  );
};
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板