React类组件fetch请求返回JSON数组后map遍历内容不显示问题
问题原因
- React类组件仅会在调用
setState()更新状态时触发重渲染,你直接给this.datosCargados、this.anotaciones赋值属于修改实例自定义属性,不会触发render方法重新执行,页面自然不会更新。 - 你在fetch请求的then回调中返回的JSX元素没有和组件渲染逻辑关联,render方法无法获取这部分内容,不可能渲染到页面上。
- 存放在state中的变量必须通过
this.state.变量名访问,你直接用this.anotaciones访问的是实例属性,和state中定义的anotaciones无关。
修正方案
- 先在组件state中初始化需要用到的状态变量
- 请求成功后调用
setState更新状态,不要直接修改实例属性 - 将列表渲染逻辑移到render方法中,从state读取数据渲染
完整修正后的组件代码如下:
import React from 'react'; export default class Apuntes extends React.Component{ // 初始化状态 state = { datosCargados: false, anotaciones: [] } getApuntes() { fetch('http://localhost:3000/GetApunte',{ method: 'GET', headers: { Accept: 'application/json', 'Content-Type': 'application/json' } }) .then(response=>response.json()) .then(responseJson => { // 调用setState更新状态,触发组件重渲染 this.setState({ datosCargados: true, anotaciones: responseJson }) }); } render(){ const { datosCargados, anotaciones } = this.state; return( <div> <button onClick={()=> this.getApuntes()}>Mostrar Apuntes</button> {/* 数据加载完成后渲染表格内容 */} {datosCargados && ( <table> <thead> <tr> <th>标题</th> <th>内容</th> </tr> </thead> <tbody> {anotaciones.map((anotacion, index)=>{ const {titulo, body} = anotacion return( <tr key={index}> <td>{titulo}</td> <td>{body}</td> </tr> ) })} </tbody> </table> )} </div> ) } }
内容的提问来源于stack exchange,提问作者P2000Gua
相关产品推荐
相关产品推荐

