无法读取未定义 REACT 的属性“地图"

2022-01-20 00:00:00 reactjs html-table fetch javascript html

构造函数(){极好的();这个.state = {清单:[],}}组件DidMount(){fetch('http://lospraianos-env-1.qu3skpxsmw.sa-east-1.elasticbeanstalk.com/api/materials').then(response => response.json()).then(resData => {this.setState({data: resData.results});})}

<table className="纯表"><头><tr><th>id</th><th>产品</th><th>Quantidade</th></tr></头><身体>{this.props.lista.map(函数(数据){返回 (<tr 键={data.codMat}><td>{data.codMat}</td><td>{data.material}</td><td>{data.qntMin}</td></tr>);})}</tbody></表></div>

我正在尝试从 API 获取信息并使用它制作一个表格,但我遇到了一些错误.

<块引用>

无法读取未定义的属性地图"

我该如何处理?

解决方案

您正在设置对代码中不存在的状态变量数据的响应.您需要将其设置为 lista 而不是 fetch Api 调用中的数据,例如

 this.setState({lista : resData.results});

在这里做条件检查和做.map

.map 没有返回

 <tbody>{this.props.lista &&this.props.lista.map(数据 => (<tr 键={data.codMat}><td>{data.codMat}</td><td>{data.material}</td><td>{data.qntMin}</td></tr>))}</tbody>

.map 带返回

 <tbody>{this.props.lista &&this.props.lista.map(data => {return (

constructor(){
    super();
    this.state = {
        lista: [],
    }
}      

componentDidMount(){
    fetch('http://lospraianos-env-1.qu3skpxsmw.sa-east-1.elasticbeanstalk.com/api/materials')
      .then(response => response.json())
      .then(resData => {
        this.setState( {data: resData.results});
      })

}

<div>
  <table className="pure-table">
    <thead>
      <tr>
        <th>id</th>
        <th>Produto</th>
        <th>Quantidade</th>
      </tr>
      </thead>
        <tbody>{
          this.props.lista.map(function(data){
            return (  
              <tr key={data.codMat}>
                <td>{data.codMat}</td>
                <td>{data.material}</td>
                <td>{data.qntMin}</td>
              </tr>
              );
            })
            }
        </tbody>
  </table>
</div>

I'm trying to get info from the API and make a table with it but I'm getting some errors.

Cannot read property 'map' of undefined

how can I deal with it?

解决方案

You are setting response to a state variable data which doesn’t exist in your code. You need to set it to lista instead of data in fetch Api call like

    this.setState({lista : resData.results});

And here do conditional check and do .map

.map without return

  <tbody>{
      this.props.lista && this.props.lista.map(data => (
          <tr key={data.codMat}>
            <td>{data.codMat}</td>
            <td>{data.material}</td>
            <td>{data.qntMin}</td>
          </tr>
        ))
        }
    </tbody>

.map with return

  <tbody>{
      this.props.lista && this.props.lista.map(data => {
          return (<tr key={data.codMat}>
            <td>{data.codMat}</td>
            <td>{data.material}</td>
            <td>{data.qntMin}</td>
          </tr>)
        })
        }
    </tbody>

相关文章