在没有Redux的情况下在REACTjs中执行GET请求很困难

时间:2016-03-13 04:22:15

标签: api http express reactjs get

我们正在构建一个使用axios对服务器执行GET请求的react应用程序(没有redux;但是使用webpack),服务器接收请求(即我们看到我们的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!');
    });

1 个答案:

答案 0 :(得分:0)

你为什么要从componentWillMount回复你的电话?我不认为你应该从生命周期事件中返回你的axios调用。我不认为它会被召唤。

实际上,您的数据通话根本不应该在您的组件中。您应该在您的动作创建者中进行数据调用,然后将其发送到您的reducer。

例如:

    // Action Creator
    import axios from 'axios'
    export const TEST = 'TEST'

    export function testApi (city) {
      return (dispatch) => {
        axios.get('/api/test').then(
          (resp) => {
            dispatch({
              type: TEST,
              payload: resp.data // or something like that
            })
          },
          (err) => {
            console.error(err)
          }
        )
      }
    }


    // Reducer
    import { TEST } from 'actions/index'

    export default function (state = {}, action) {
      switch (action.type) {
        case TEST:
          return Object.assign({}, state, action.payload)
      }

      return state
    }


    // Component
    componentWillMount () {
      this.props.dispatch(testApi())
    }
相关问题