【问题标题】:Data are not rendering in Component with react router使用反应路由器在组件中未呈现数据
【发布时间】:2019-07-15 18:08:05
【问题描述】:

我遇到了 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,有什么想法吗?在此先感谢您的帮助,我已经卡了很长时间了。

【问题讨论】:

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


    【解决方案1】:

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

    换一个怎么样

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

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

    ?

    请参阅Usage of the backtick character (`) in JavaScript? 以获得更详细的说明。

    【讨论】:

    • 需要反引号来创建模板文字字符串,以便将 id 作为变量传递
    【解决方案2】:

    我会让您的组件有状态,以便更轻松地正确处理异步 API 调用。确保等待、更新状态,然后使用作为 props 传递的 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
           } 
         }
      }
    
    
    
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 2022-08-22
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多