ReactJs在调用api后不会将数据生成到视图中

ReactJs在调用api后不会将数据生成到视图中,reactjs,Reactjs,我刚刚了解了reactjs,我不明白为什么我的代码不是错误的,但它不能呈现数据以供查看 我尝试了显示测试功能。它工作正常, 但是在getAllProducts函数中,调用api后,似乎无法更新页面上的html代码 我怎么了 这是我的密码: import React from 'react'; class ListObject extends React.Component { getAllProducts() { fetch("http://5bd054ce142d36

我刚刚了解了reactjs,我不明白为什么我的代码不是错误的,但它不能呈现数据以供查看

我尝试了显示测试功能。它工作正常, 但是在getAllProducts函数中,调用api后,似乎无法更新页面上的html代码

我怎么了

这是我的密码:

import React from 'react';
class ListObject extends React.Component {

    getAllProducts() {
        fetch("http://5bd054ce142d360013a172f3.mockapi.io/api/products")
            .then(res => res.json())
            .then((result) => {

                // return (<h1>Why not display????</h1>);
                result.map(
                    (product, i) => {
                        return <TableRow key={i} data={product} />
                    }
                )
            },
                (error) => {
                    return "errrr";
                }
            )
    }

    test() {
        return (<h1>Hello World</h1>);
    }

    render() {
        return (
            <div className="container-fluid">
                <table className="table table-hover">
                    <thead>
                        <tr>
                            <th>Id</th>
                            <th>Name</th>
                            <th>Avatar</th>
                            <th>Created At</th>
                        </tr>
                    </thead>
                    <tbody>
                        {this.getAllProducts()}
                    </tbody>
                </table>
                {this.test()}
            </div>
        );
    };
}


class TableRow extends React.Component {
    render() {
        return (
            <tr>
                <td>{this.props.data.id}</td>
                <td>{this.props.data.name}</td>
                <td>{this.props.data.avatar}</td>
                <td>{this.props.data.createdAt}</td>
            </tr>
        );
    };
}

export default ListObject
从“React”导入React;
类ListObject扩展了React.Component{
getAllProducts(){
取回(“http://5bd054ce142d360013a172f3.mockapi.io/api/products")
.then(res=>res.json())
。然后((结果)=>{
//返回(为什么不显示??);
result.map(
(产品,i)=>{
返回
}
)
},
(错误)=>{
返回“errrr”;
}
)
}
测试(){
返回(你好世界);
}
render(){
返回(
身份证件
名称
阿凡达
创建于
{this.getAllProducts()}
{this.test()}
);
};
}
类TableRow扩展了React.Component{
render(){
返回(
{this.props.data.id}
{this.props.data.name}
{this.props.data.avatar}
{this.props.data.createdAt}
);
};
}
导出默认ListObject

更改getAllProducts并向组件添加状态对象,如下所述。API调用是异步的,所以不能直接返回它。您可以使用组件状态。并在componentDidMount中进行api调用以获取api数据

class ListObject extends React.Component {
  state = {
    result: []
  };
  componentDidMount() {
    this.getAllProducts();
  }
  getAllProducts() {
    return fetch("https://5bd054ce142d360013a172f3.mockapi.io/api/products")
      .then(res => res.json())
      .then(result => {
        // return (<h1>Why not display????</h1>);
        this.setState({
          result
        });
      })
      .catch(e => {
        //dispatch some action to showcase error or
        //make state update using setState to show error
        return null;
      });
  }
  getProductListUI = () => {
    const { result } = this.state;
    return result.map((product, i) => <TableRow key={i} data={product} />);
  };
  test() {
    return <h1>Hello World</h1>;
  }

  render() {
    return (
      <div className="container-fluid">
        <table className="table table-hover">
          <thead>
            <tr>
              <th>Id</th>
              <th>Name</th>
              <th>Avatar</th>
              <th>Created At</th>
            </tr>
          </thead>
          <tbody>{this.getProductListUI()}</tbody>
        </table>
        {this.test()}
      </div>
    );
  }
}

class TableRow extends React.Component {
  render() {
    return (
      <tr>
        <td>{this.props.data.id}</td>
        <td>{this.props.data.name}</td>
        <td>{this.props.data.avatar}</td>
        <td>{this.props.data.createdAt}</td>
      </tr>
    );
  }
}

ReactDOM.render(<ListObject />, document.getElementById("root"));
类ListObject扩展了React.Component{
状态={
结果:[]
};
componentDidMount(){
这个.getAllProducts();
}
getAllProducts(){
返回取回(“https://5bd054ce142d360013a172f3.mockapi.io/api/products")
.then(res=>res.json())
。然后(结果=>{
//返回(为什么不显示??);
这是我的国家({
结果
});
})
.catch(e=>{
//发送一些操作以显示错误或错误
//使用setState进行状态更新以显示错误
返回null;
});
}
getProductListUI=()=>{
const{result}=this.state;
返回result.map((产品,i)=>);
};
测试(){
返回你好世界;
}
render(){
返回(
身份证件
名称
阿凡达
创建于
{this.getProductListUI()}
{this.test()}
);
}
}
类TableRow扩展了React.Component{
render(){
返回(
{this.props.data.id}
{this.props.data.name}
{this.props.data.avatar}
{this.props.data.createdAt}
);
}
}
render(,document.getElementById(“根”));
以下是代码笔链接的工作方式:
反馈欢迎感谢

更改getAllProducts并向组件添加状态对象,如下所述。API调用是异步的,所以不能直接返回它。您可以使用组件状态。并在componentDidMount中进行api调用以获取api数据

class ListObject extends React.Component {
  state = {
    result: []
  };
  componentDidMount() {
    this.getAllProducts();
  }
  getAllProducts() {
    return fetch("https://5bd054ce142d360013a172f3.mockapi.io/api/products")
      .then(res => res.json())
      .then(result => {
        // return (<h1>Why not display????</h1>);
        this.setState({
          result
        });
      })
      .catch(e => {
        //dispatch some action to showcase error or
        //make state update using setState to show error
        return null;
      });
  }
  getProductListUI = () => {
    const { result } = this.state;
    return result.map((product, i) => <TableRow key={i} data={product} />);
  };
  test() {
    return <h1>Hello World</h1>;
  }

  render() {
    return (
      <div className="container-fluid">
        <table className="table table-hover">
          <thead>
            <tr>
              <th>Id</th>
              <th>Name</th>
              <th>Avatar</th>
              <th>Created At</th>
            </tr>
          </thead>
          <tbody>{this.getProductListUI()}</tbody>
        </table>
        {this.test()}
      </div>
    );
  }
}

class TableRow extends React.Component {
  render() {
    return (
      <tr>
        <td>{this.props.data.id}</td>
        <td>{this.props.data.name}</td>
        <td>{this.props.data.avatar}</td>
        <td>{this.props.data.createdAt}</td>
      </tr>
    );
  }
}

ReactDOM.render(<ListObject />, document.getElementById("root"));
类ListObject扩展了React.Component{
状态={
结果:[]
};
componentDidMount(){
这个.getAllProducts();
}
getAllProducts(){
返回取回(“https://5bd054ce142d360013a172f3.mockapi.io/api/products")
.then(res=>res.json())
。然后(结果=>{
//返回(为什么不显示??);
这是我的国家({
结果
});
})
.catch(e=>{
//发送一些操作以显示错误或错误
//使用setState进行状态更新以显示错误
返回null;
});
}
getProductListUI=()=>{
const{result}=this.state;
返回result.map((产品,i)=>);
};
测试(){
返回你好世界;
}
render(){
返回(
身份证件
名称
阿凡达
创建于
{this.getProductListUI()}
{this.test()}
);
}
}
类TableRow扩展了React.Component{
render(){
返回(
{this.props.data.id}
{this.props.data.name}
{this.props.data.avatar}
{this.props.data.createdAt}
);
}
}
render(,document.getElementById(“根”));
以下是代码笔链接的工作方式:
反馈欢迎感谢

您似乎完全弄错了。在React中,您需要根据组件的
状态
道具
呈现数据。所以,你必须这样做:

class YourComponent extends React.Component {
  getAllProducts() {
    // you can handle a "loading" state as well
    this.setState({isLoading: true});
    fetch("http://example.com/api/products")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            products: result,
            isLoading: false,
          });
        },
        (error) => {
          return this.setState({hasError: true, error})
        }
      );
    }
  }
  componentDidMount() {
    fetchAllProducts();
  }
  render() {
    const {products, isLoading, hasError} = this.state;

    if (hasError) {
      return (
        <p>Something bad happened</p>
      );
    }

    if (isLoading) {
      return (
        <p>Hey, we're fetching data...</p>
      );
    }
    return (
      <table>
        {products.map(p => <TableRow ... />)
      </table>
    )
  }
}
class YourComponent扩展了React.Component{
getAllProducts(){
//您还可以处理“加载”状态
this.setState({isLoading:true});
取回(“http://example.com/api/products")
.then(res=>res.json())
.那么(
(结果)=>{
这是我的国家({
产品:结果,,
孤岛加载:false,
});
},
(错误)=>{
返回此.setState({hasError:true,error})
}
);
}
}
componentDidMount(){
fetchAllProducts();
}
render(){
const{products,isLoading,hasrerror}=this.state;
if(hasrerror){
返回(
发生了不好的事

); } 如果(孤岛加载){ 返回( 嘿,我们正在获取数据

); } 返回( {products.map(p=>) ) } }
注意