【问题标题】:Unable to render the data from API on first mount首次挂载时无法从 API 呈现数据
【发布时间】:2023-03-30 20:25:01
【问题描述】:

我正在使用 axios 在我的 react 应用程序中获取数据。我需要在组件安装后立即呈现数据列表。从 API 获取的数据在我的本地主机中运行良好。但是,一旦我的应用程序投入生产,就不会调用第一次安装时获取的数据,即最初不会从 API 中获取数据。它显示空白。我必须刷新页面才能加载数据。

我尝试了多种使用 axios 调用 API 的方法,例如返回 Promise 和使用 try-catch 块,甚至根据响应状态进行条件数据调用,但每次问题都一样。

这就是我的组件的运行方式:

class Users extends Component {

  constructor(props) {
    super(props);

    this.state = {
        usersData: [],
        dataFetched: false,
        renderData: false,
        current_page: 1,
        total_data: '',
        per_page: 5,
        currentUsers: [],
        searchUser: ''
    };
  }


  componentDidMount(){
    this.fetchUsers();
  }

  fetchUsers = async () => {

    await axios.get(GlobalData.BASE_URL+'api/user/list', {headers:GlobalData.headers})
    .then(res => {
        this.setState({ 
            usersData: res.data.data, 
            total_data: res.data.data.length,
            dataFetched: res.data.status,
            renderData: true 
        }, () => this.formatData());

    })
    .catch(err => console.log(err));
  }


  formatData() {
    const indexOfLastPost = this.state.current_page * this.state.per_page;
    const indexOfFirstPage = indexOfLastPost - this.state.per_page;

    const currentUsers = this.state.usersData.slice(
      indexOfFirstPage,
      indexOfLastPost
    );
    this.setState({ currentUsers });
  }


  handleClick = number => {
    this.setState({
      current_page: number
    }, () => {
      this.formatData();
    });
  };


  setID = (e) => {
    // console.log(e.target.id)
    var fetched_id = e.target.id;
    this.setState({fetched_id}, () => this.getMsgList(fetched_id));

    //console.log(e.target.id)
}

  getMsgList = (fetched_id) => {
    if(fetched_id){
      this.props.history.push({
      pathname: '/users/userdetail',
      search: '?user='+fetched_id
      });
  }
}


  handleInput = (e) => {
    let input_status = e.target.value;

    this.setState({
      searchUser: input_status
    });
  }


  render() {
    let filteredUserStatus = this.state.currentUsers.filter( e => {
      return e.status.toLowerCase().includes(this.state.searchUser.toLowerCase());
    });

    console.log(filteredUserStatus)

    const { per_page, total_data, current_page, currentUsers }  = this.state;

    return (
      <div className="animated fadeIn">
        <Row>
          <Col xl={12}>
            <Card>
              <CardHeader>
                  <Row>
                    <Col lg="8">
                      <h4>Users List</h4>
                    </Col>

                    <Col lg="4" md="12">
                        <Input type="text" placeholder="Search user status..." className="search_box" onChange={this.handleInput} />
                    </Col>
                  </Row>

                  <Row style={{marginTop: 15}}>
                    <Col lg="12">
                      <Button className="float-right" onClick={()=>this.props.history.push('/users/createuser')}>Create User</Button>
                    </Col>
                  </Row>
              </CardHeader>
              <CardBody>
                <Table responsive hover>
                  <thead>
                    <tr>
                      <th scope="col">S.No</th>
                      <th scope="col">User Name</th>
                      <th scope="col">First Name</th>
                      <th scope="col">Last Name</th>
                    </tr>
                  </thead>
                  <tbody>
                  { total_data ?
                        currentUsers.map( (datum, i) => (

                        <tr className="data-slice" key={i}>
                            <td>{datum.id}</td>
                            <td>{datum.user_name}</td>
                            <td>{datum.first_name}</td>
                            <td>{datum.last_name}</td>
                            <td>
                              <Button id={datum.id} color="primary" onClick={this.setID}><i className="icon-pencil"></i></Button>
                              <Button id={datum.id} color="danger" onClick={()=>alert('Item to be deleted!')}><i className="fa fa-times"></i></Button>
                            </td>
                        </tr>
                        ))
                        : <tr><td>No Data!</td></tr>
                    }
                  </tbody>

                </Table>
                {
                  this.state.renderData === true ? 
                    <CustomPagination
                      per_page={per_page}
                      current_page={current_page}
                      total_data={total_data}
                      handleClick={this.handleClick}
                    />
                :
                null
                }

              </CardBody>
            </Card>
          </Col>
        </Row>
      </div>
    )
  }
}

export default Users;

另外,我的网页托管在不安全的服务器上,如果这是导致数据获取不当的原因? 请帮助确定问题。

【问题讨论】:

  • 第一次不工作怎么办?您是否遇到过 API 的任何错误? @泡泡绳
  • API 没有问题。我第一次这么说是因为它适用于本地但不适用于生产。

标签: reactjs axios


【解决方案1】:

你能试试这样的吗?

constructor(props) {
    super(props);
    this.state = {
      data: {}
    };
  }

  componentDidMount() {
    fetch("https://my-json-server.typicode.com/Rotarepmi/exjson/db")
      .then(res => res.json())
      .then(json => {
        this.setState({ json });
      });
  }

【讨论】:

  • 使用这种方法会有什么不同?如果你解释?表单API返回的数据已经在axios中转成JSON格式
猜你喜欢
  • 1970-01-01
  • 2021-10-29
  • 2014-02-24
  • 1970-01-01
  • 2018-03-01
  • 2018-09-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多