数据未在 React 组件中呈现

Data are not rendering in react component

我正在尝试根据我在 url 中传递的 ID 呈现一些数据,当我 console.log() res.json 我可以访问数据但我有不知道如何传递给 'articleComponent'

const Articles = () => {


  const query = (id) => {
    fetch(`https://someurl.herokuapp.com/job/${id}`).then(res => console.log(res.json()))
  }


  const pathname = window.location.pathname.split('/');
  const job_id = pathname[pathname.length - 1];
  const job = query(job_id);
  let position_name;
  let workplace_name;
  console.log(job_id)
  if (job) {
    position_name = position_name;
    workplace_name = workplace_name;
  }


  return (
    <ArticleComponent
      position_name={position_name}
      workplace_name={workplace_name}
    />
  );
};

export default Articles

console.log() 正在返回 'pending but i can see all the object'

当我单击此 link 时,我可以访问此组件:

    <Link
          className="link-apply"
          to={{pathname: `/job/${job._id}`,
                          state: job
                        }}>
                        <p className="place">{job.workplace_name}</p>
                        <p className="location-job">{job.location}</p>
                      </Link>

您没有对获取调用的响应执行任何操作。

当 React 组件是功能组件(与 class 组件相反)时,该功能本身就是渲染功能。这是一个同步函数,所以你不能只在函数体中进行异步调用。

例如,当组件进入componentDidMount生命周期钩子时,可以调用fetch函数,每当returns,就可以将结果存入组件状态(使用setState 用于 class 组件或 useState 挂钩(如果它是功能组件)。

所以:

class Articles extends React.Component {
  state = {
    data: undefined
  };

  componentDidMount() {
    const id = "some value";
    fetch(`https://someurl.herokuapp.com/job/${id}`)
      .then(res => res.json())
      .then(response => this.setState({ data: response }));
  }

  render() {
    const pathname = window.location.pathname.split('/');
    const job_id = pathname[pathname.length - 1];
    const job = query(job_id);
    let position_name;
    let workplace_name;
    console.log(job_id)
    if (job) {
      position_name = position_name;
      workplace_name = workplace_name;
    }


    return (
      <ArticleComponent
        data={this.state.data}
        position_name={position_name}
        workplace_name={workplace_name}
      />
    );
  }
};

export default Articles

你必须将加载逻辑和渲染分开。 在您使用组件功能的情况下,您应该

  1. 使用 useState(null) 为您的数据创建状态,其中 null 是初始状态

  2. 使用 useEffect 开始在组件挂载上获取数据,其中 [] 作为第二个参数告知你的 useEffect 不依赖于任何值的反应,应该 运行 仅在组件挂载上一次

import React, { useEffect, useState } from 'react';

const query = async (id, onFetchData) => {
  const res = await fetch(`https://someurl.herokuapp.com/job/${id}`);
  const data = await res.json();
  onFetchData(data);
}

const getJobId = () => {
  const pathname = window.location.pathname.split('/');
  return pathname[pathname.length - 1];
}

const Articles = () => {
  const [job, setJob] = useState(null);
  useEffect(() => {
    query(getJobId(), setJob);
  } ,[]);

  return <>{
      job
      ? <ArticleComponent
        position_name={job.position_name}
        workplace_name={job.workplace_name}
      />
      : <span>loading...</span>
     }</>
};

export default Articles
Hi @Erwin,

Here is the working example for your query. Checkout the CodeSandbox - [https://codesandbox.io/s/mystifying-wave-qxrnp][1]

只需将 API 端点替换为您想要的端点。希望这对您有所帮助!

import React from "react";
import ReactDOM from "react-dom";
import ArticleComponent from "./ArticleComponent";
import "./styles.css";

class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      data: undefined
    };
  }

  componentDidMount() {
    const pathname = window.location.pathname.split("/");
    const job_id = pathname[pathname.length - 1];
    console.log(job_id);
    fetch("https://jsonplaceholder.typicode.com/todos/1")
      .then(response => response.json())
      .then(json => this.setState({ data: json }));
  }

  render() {
    return this.state.data ? (
      <ArticleComponent data={this.state.data} />
    ) : (
      "Loading"
    );
  }
}

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