【问题标题】:Axios ReactJs Laravel: How to retrieve the multiple request ApiAxios ReactJs Laravel:如何检索多个请求 Api
【发布时间】:2018-09-07 00:53:52
【问题描述】:

我创建了新的 laravel 项目并结合了 React Javascript 框架。 我看 youtube 并阅读一些网站,了解如何使用 Axios HTTP Requests API。 但是他们没有讨论如何使用 axios 来检索多个请求 api。

问题:

如何检索多个请求 api,并且我想将其显示到我的渲染函数中

我在我的Home Controller中创建了两个公共函数(Mission、Store)。

public function mission() {
    $content_mission = DB::table('content_structure')
    ->where('content_pages','=','Home')
    ->where('content_section','=','Mission-Vision')
    ->where('status','=','Active')
    ->orderBy('content_id','Desc')
    ->limit(1)
    ->get();

    return response()->json($content_mission);
}


public function store() {
    $content_store = DB::table('content_structure')
    ->leftJoin('content_upload_assets','content_structure.content_id','=','content_upload_assets.cid')
    ->where('content_pages','=','Home')
    ->where('content_section','=','Store')
    ->where('status','=','Active')
    ->orderBy('content_id','Desc')
    ->limit(1)
    ->get();

    return response()->json($content_store);
}

我还在我的组件文件夹中创建了 Index.js。

constructor() {
    super();
    this.state = {

    }

  }

  componentWillMount() {

    this.setState({
      missionsApiRes: []
    });

    Promise.all([
      axios.get('/api/mission'),
      axios.get('/api/store')
    ]).then(response => {
      const [storesApiRes, missionsApiRes] = response;
      this.setState({storesApiRes,missionsApiRes}, () => {

      });
    })
  }



  renderMission() {
    return this.state.missionsApiRes.map(mission => 
      <div>{mission.content}</div>
    )
  }

我的渲染功能:

 <div className="container">
     {this.renderMission()}
 </div>

错误:

未捕获的类型错误:this.state.missionsApiRes.map 不是函数

【问题讨论】:

  • 这通常发生在“missionsApiRes”返回一个对象时。我认为 map 函数适用于 Array

标签: javascript reactjs laravel


【解决方案1】:

我会说你的this.state.missionsApiRes 在调用render 时没有定义。尝试将其移至构造函数:

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

【讨论】:

    【解决方案2】:

    需要 axios promise 的自定义解析数据

    Promise.all([
      axios.get('/api/mission'), => axios.get('/api/mission').then(data => data)
    

    【讨论】:

      猜你喜欢
      • 2016-11-26
      • 2021-01-20
      • 2017-10-26
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      相关资源
      最近更新 更多