首页 > 解决方案 > map() 不返回任何内容

问题描述

在 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>
    )
}
}

annotaciones 在州内,这就是我使用 this.anotaciones 的原因

标签: javascriptreactjs

解决方案


而不是在承诺中返回 JSX,只需将 annotaciones 保存到状态中。您可以将表的生成提取到单独的函数中,例如

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()}
            </>
        )
    }
}

推荐阅读