使用React Router无法在Component中呈现数据

时间:2019-07-15 18:08:05

标签: reactjs react-router react-router-v4 react-router-dom

我遇到了React Router的问题,我试图在卡中渲染组件,但是由于某些原因,数据无法显示:

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

在单击此链接时,我要呈现此链接:

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;

  if (job) {
    position_name = job.position_name;
    workplace_name = job.workplace_name;
  }


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

一切都显示在console.log上,但是由于某种原因,该作业没有定义,所以我无法将任何数据传递给ArticleComponent,有什么想法吗?预先感谢您的帮助,我已经呆了很长时间了。

2 个答案:

答案 0 :(得分:0)

您确定问题不是由反引号(`)引起的吗?

如何更改

fetch(`https://someurl.herokuapp.com/job/${id}`).

fetch("https://someurl.herokuapp.com/job/${id}").

有关详细说明,请参见Usage of the backtick character (`) in JavaScript?

答案 1 :(得分:0)

我将使您的组件处于有状态,以便更轻松地正确处理异步API调用。确保您等待,更新状态,然后使用作为道具传递的api结果数据正确呈现组件。另外,在Link组件中使用react router的search属性,可以轻松访问查询参数。

<Link
  to={{
    pathname: // set path
    search: { job_id: 1 }
    state: // set any initial state your'd like to pass
  }}
/>

/////

class Article extends React.Component {
   constructor(props) {
     super(props)
     this.state.apiRes = null;
   }

  async ComponentDidMount() {
    const id = this.props.match.params.job_id
    const apiRes = await fetch(`https://someurl.herokuapp.com/job/${id}`).then(res => res.json()).then(finalRes => finalRes);
    this.setState({ apiRes })
  }

   render() {
      if(this.state.apiRes) {
          const position_name = this.state.apiRes.position_name
          const workpalce_name = this.state.apiRes.workplace_name  
       return (
         <ArticleComponent
           position_name={position_name || null}
           workplace_name={workplace_name || null }
         />
        );
       } else {
        return null
       } 
     }
  }