从componentDidMount中的api获取数据返回null

时间:2019-04-18 06:25:40

标签: javascript reactjs api

我正在尝试以componentDidMount生命周期的反应方法来获取数据,但没有得到。

我的方法是:

  componentDidMount() {
    const { taskId } = this.props
    getTask(taskId)
    .then(data => {
        console.log(data);
      this.setState({task: data});
    })
  }

我的api是:

  export const getTask = (unique_id) =>  {
  console.log(unique_id)
    return fetch('https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/'+ unique_id).then(res => { 
    return res.json();
    });
  };

这是我的全部内容:

import React, { Component } from 'react'
import { getTask } from '../../modules/clients';
import ClientTaskShow from '../../components/tasks/ClientTaskShow'

class ClientTaskShowContainer extends Component {
  constructor(props) {
    super(props)

    this.state = {
      messageModalOpen: false,
      selectedPartnerId: null,
      task:{}
    }
  }

  componentDidMount() {
      console.log("hello")
    const { taskId } = this.props
    getTask(taskId)
    .then(data => {
        console.log(data);
      this.setState({task: data});
    })
  }
  render() {
    const taskSelected = this.state.task;
    console.log(taskSelected)
        return (
            <ClientTaskShow 
                task={taskSelected}
            />
        )   
  }
}

export default ClientTaskShowContainer;

从其中调用clienttaskShowContainer的代码:

import React from 'react'
import Head from 'next/head'
import Layout from '../../components/Layout'
import ClientTaskShowContainer from '../../containers/tasks/ClientTaskShowContainer'
import requireAuth from '../../lib/requireAuth'

const ClientTasksShow = ({ query }) => {
  const { taskId } = query
  return (
    <Layout fluid fullHeight clientTaskHeader='true'>
      <Head>
        <title>Client Task Details | Punctual</title>
      </Head>
      <ClientTaskShowContainer taskId={taskId} />
    </Layout>
  )
}

ClientTasksShow.getInitialProps = async ({ query }) => ({
    query
  })

export default requireAuth(ClientTasksShow)

我认为它甚至没有达到API。尽管它一次命中,但我没有重新启动服务器。我无法复制该问题。 在某些网站上,我发现应该使用.then进行API调用,而其他网站则说我们不能在componentDidMount的API调用中传递边界。确切的解决方案是什么?请帮忙。预先感谢。

3 个答案:

答案 0 :(得分:1)

实际上可以正常工作

enter image description here

console.log(data)从api返回错误消息

答案 1 :(得分:1)

此代码有效

//调用组件

import React from "react";
import CallComp from "./CallComp";
import ReactDOM from "react-dom";

function App() {
  return (
    <div className="App">
      <CallComp taskId={"7693fbf81a33"} />
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

//子组件

import React, { Component } from "react";
import ClientTaskShow from "./ClientTaskShow";

class ClientTaskShowContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      task: {}
    };
  }

  componentDidMount() {
    const { taskId } = this.props;
    fetch(
      `https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/${taskId}`
    )
      .then(response => response.json())
      .then(data => this.setState({ task: data }))
      .catch(error => console.log("the error is", error));
  }
  render() {
    const taskSelected = this.state.task;
    console.log("task selected is ", taskSelected);
    return (
      <div>
        {Object.keys(taskSelected).length ? (
          <ClientTaskShow task={taskSelected} />
        ) : (
          <div>No data to show</div>
        )}
      </div>
    );
  }
}

export default ClientTaskShowContainer;

//演示ClientTaskShow

import React from "react";

const ClientTaskShow = ({ task }) => {
  return <h1>{task.unique_code}</h1>;
};

export default ClientTaskShow;

答案 2 :(得分:0)

您应该从函数返回promise,以了解api请求是否已解决

尝试:

export const getTask = (id) => {
    return new Promise(function (resolve, reject) {
        fetch('https://punctual-backend-staging.herokuapp.com/api/v1/homeowner_tasks/' + id).then((res) => {
            resolve(res.json())
        })
    });
}

然后这样呼叫:

componentDidMount() {
    getTask(1).then((data)=>{
        console.log(data);
    });  
}

您可以使用ID替换参数

希望这会有所帮助。