【问题标题】:Difficulty performing GET requests in REACTjs without Redux在没有 Redux 的情况下难以在 REACTjs 中执行 GET 请求
【发布时间】:2016-06-28 05:53:36
【问题描述】:

我们正在构建一个 react 应用程序(没有 redux;但使用 webpack),它使用 axios 向服务器发出 GET 请求,服务器接收请求(即我们看到我们的 console.log 语句)但对请求永远不会被服务,因为除了我们的 console.log 之外我们没有得到任何数据。服务器似乎对我们的 response.end/response.send 语句没有做任何事情。

以前有没有人处理过这个问题?有人有任何提示吗?请在下面查看我们的代码。

//Within our react component file

componentWillMount (){

      console.log("inside of componentWillMount!");

      return axios.get('/api/test')
      .then(function(resp){
        return resp.data;
        console.log('axios response: ', resp);
      })
      .catch(function(resp) {
        console.log('axios catch response ', resp);
      });
    }




//From our server.js file


    // additional middleware to set headers that we need on each request
    app.use(function(req, res, next) {

      // disable caching so we'll always get the latest activities
      res.setHeader('Cache-Control', 'no-cache');
      next();
    });

    app.get('/api/test', function(request, response, err) {
      //mongoose find all here
      console.log("We're in the server!!!");

      response.end("ennnndddd");

      if(err){
        console.log("ERROR!", err);
      }
    });




    app.listen(port, function () {
     console.log('Proxy listening on port 3000!');
    });

【问题讨论】:

    标签: api http express reactjs get


    【解决方案1】:

    您为什么要从 componentWillMount 回电?我认为您不应该从该反应生命周期事件中返回您的 axios 调用。我认为它永远不会被调用。

    实际上,您的数据调用根本不应该在您的组件中。您应该在您的动作创建者中进行数据调用,然后将其分派给您的减速器。

    例如:

    // 动作创建者 从'axios'导入axios 导出常量测试 = '测试' 导出函数 testApi (city) { 返回(调度)=> { axios.get('/api/test').then( (resp) => { 派遣({ 类型:测试, 有效载荷:resp.data //或类似的东西 }) }, (错误)=> { 控制台错误(错误) } ) } } // 减速器 从“操作/索引”导入 { TEST } 导出默认函数(状态 = {},操作){ 开关(动作类型){ 案例测试: 返回 Object.assign({}, state, action.payload) } 返回状态 } // 零件 组件WillMount () { this.props.dispatch(testApi()) }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-26
      • 1970-01-01
      • 1970-01-01
      • 2011-12-06
      • 2019-09-04
      相关资源
      最近更新 更多