【问题标题】:map() does not return anythingmap() 不返回任何内容
【发布时间】:2021-11-01 22:14:50
【问题描述】:

在 onClick 按钮中,我有一个函数可以发出 GET 请求并接收 json 数组。当我尝试向用户显示它时,没有任何变化,尽管如果我将 console.log 放在地图中,我会显示并遍历所有对象。

fetch('http://localhost:3000/GetApunte',{
            method: 'GET',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json'
            }
        })
        .then(response=>response.json())
        .then(responseJson => {            
            this.datosCargados=true;
            this.anotaciones=responseJson;
            //cuerpo()
            
                return(
                    <tbody>
                        {this.anotaciones.map((anotacion, index)=>{
                            const {titulo, body} = anotacion
                            return(
                                <tr key={index}>
                                    <td>{titulo}</td>
                                    <td>{body}</td>
                                </tr>
                            )
                        })}
                    </tbody> 
                );
        });

我的班级结构是这样的:

export default class Apuntes extends React.Component{
state ={}
getApuntes(){}

render(){
    return(
        <button onClick={()=> this.getApuntes()}>Mostrar Apuntes</button>
    )
}
}

anotaciones 在状态内部,这就是我使用 this.anotaciones 的原因

【问题讨论】:

  • 一般来说,您希望在数据进入时设置状态。因此,即使您在某处 return fetch... 此处显示的所有内容,您仍然只需要一个 Promise 的 JSX到await.then
  • 从你的异步函数返回一个 JSX &lt;tbody&gt; 不会把它添加到文档中。您应该做的是使用远程数据更新 state 并在渲染的 HTML 中呈现该状态
  • 您正在从 fetch 返回一个 JSX,并且您没有以任何方式使用结果。
  • 这行this.anotaciones=responseJson;是非法的,你不能直接改变状态。此外,正如 zhulien 指出的那样,您没有呈现您的获取结果

标签: javascript reactjs


【解决方案1】:

你不能简单地将数据从 Promise 直接返回到 React 组件,因为在异步函数和同步组件之间控制数据流状态并不容易。 试试这个做法:

const [arr, setArr] = useState([]) // array empty on init
async fetch() {
    return fetchedArray; // get array from remote 
}

useEffect(() => {
   fetchdArray().then(fetchedArr => setArr(fetchedArr);
}, []); // this is equal to componentDidMount in class component

return (<div>{arr.map(...)}</div>)

通过这种方式,arr 始终将其状态更新到屏幕,从空到填充

【讨论】:

    【解决方案2】:

    不要在 promise 中返回 JSX,只需将 annotaciones 保存到 state 中。您可以将表的生成提取到单独的函数中,例如

    const generarAnotaciones = () =>
        <tbody>
            {this.anotaciones.map((anotacion, index) => {
                const { titulo, body } = anotacion
                return (
                    <tr key={index}>
                        <td>{titulo}</td>
                        <td>{body}</td>
                    </tr>
                )
            })}
        </tbody>
    

    那么你的类应该是这样的:

    export default class Apuntes extends React.Component {
        state = {}
        getApuntes() { }
    
        render() {
            return (
                <>
                    <button onClick={() => this.getApuntes()}>Mostrar Apuntes</button>
                    {generarAnotaciones()}
                </>
            )
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2018-12-29
      • 2018-10-24
      • 1970-01-01
      • 2021-10-02
      • 2020-04-27
      • 2019-04-06
      • 2012-02-15
      • 2020-09-07
      • 2021-11-22
      相关资源
      最近更新 更多