基于this.props.params.id

时间:2016-10-03 12:02:24

标签: javascript reactjs

我有以下组件:

import React from 'react';

import porgectsCollection from './../data/projectInfo.js';

class SingleProject extends React.Component {
  getProjectId() {
    let projectID = porgectsCollection.filter(el => {
        return (el.title = {this.props.params.id});
    });
  }
  render () {
    console.log(this.getProjectId);
    return (
        <div>
            <h2>{this.props.params.id}</h2>
        </div>
    );
  }
}

export default SingleProject;

和我的routes.jsx如下:

import React from 'react';
import { Route, Router, IndexRoute } from 'react-router';
import ReactDOM from 'react-dom';

import Wrapper from './../wrapper.jsx';
import Home from './../home.jsx';
import Projects from './../projects.jsx';
import SingleProject from './../singleProject.jsx';

ReactDOM.render((
    <Router>
        <Route component={Wrapper} >
            <Route path="/" component={Home} />
            <Route path="projects" component={Projects} />
            <Route path="projects/:id" component={SingleProject} />
        </Route>
    </Router>
), document.getElementById('app'));

根据传入的ID:

<Route path="projects/:id" component={SingleProject} />

我希望获得该值并过滤来自以下的数组:

import porgectsCollection from './../data/projectInfo.js';

然后我尝试使用此功能:

  getProjectId() {
    let projectID = porgectsCollection.filter(el => {
        return (el.title = {this.props.params.id});
    });
  }

显示正确的数据。

我不确定这是否是正确的方法,但是当我运行webpack时我也遇到错误:

引用{this.props.params.id}的意外令牌

1 个答案:

答案 0 :(得分:2)

你不应该需要括号 - 它只是一个普通的JS函数:

  getProjectId() {
    let projectID = porgectsCollection.filter(el => {
        return el.title === this.props.params.id;
    });
  }

一些更有光泽的格式:

  getProjectId() {
    return porgectsCollection.filter(el => el.title === this.props.params.id);
  }

(你也在&#34;项目&#34中写错了;但我让它保持一致)