简体   繁体   English

数据未在React组件中呈现

[英]Data are not rendering in react component

I'm trying to render some data depending on the id that i pass in the url , when i console.log() the res.json I have access to the data but I have no idea how to pass to the 'articleComponent' 我正在尝试根据我在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

the console.log() is returning 'pending but i can see all the object' console.log()返回“待处理,但我可以看到所有对象”

i have access to this component when i click this 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>

You're not doing anything with the response of the fetch call. 您对fetch调用的响应没有做任何事情。

When a React component is a functional component (as opposed to a class component), the function itself is the render function. 当React组件是功能组件(而不是类组件)时,该函数本身就是render函数。 This is a synchronous function, so you can't just have an async call in the function body. 这是一个同步函数,因此您不能只在函数主体中进行异步调用。

For example, when the component enters the componentDidMount lifecycle hook, you can call the fetch function, and whenever it returns, you can store the result in the component state (use setState for class component or the useState hook if it's a functional component). 例如,当组件进入componentDidMount生命周期挂钩时,您可以调用fetch函数,并且每当返回时,您都可以将结果存储在组件状态中(将setState用于类component或将useState挂钩用作功能组件)。

So: 所以:

 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 

You have to separate loading logic and render. 您必须分开加载逻辑和渲染。 In your case you are using Component function, you should 如果您使用的是Component函数,则应

  1. Create state for your data with useState(null), where null is initial state 使用useState(null)为数据创建状态,其中null为初始状态

  2. Use useEffect to start fetching data on component mount, where [] as second argument inform react what your useEffect not depends on any value and should run only once on component mount 使用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]

Just replace the API Endpoint with your desired one. 只需将API端点替换为所需的端点即可。 Hope this helps! 希望这可以帮助!

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM