如何通过路由器传递道具

时间:2019-02-11 20:04:07

标签: reactjs react-router

我在仪表板上有一个任务列表,我想尽快单击任务以获取他的详细信息。

目前,我只能检索此任务的ID,但无法获取其他信息。

当我在父组件上console.log listTask 时,我得到一个包含所有任务的Array对象:

[ 0: Object { state: "Started", date: "2019-02-11T19:57:26.176Z", _id:         "5c6074afd2f8eb5019fd5f54", … }
1: Object { state: "Started", date: "2019-02-11T19:57:26.176Z",                     _id:"5c60798bacf119510c19f5b1", … }
2: Object { state: "Started", date: "2019-02-11T19:57:26.176Z", _id: "5c607be3c11c2b529615ac26", … }
3: Object { state: "Started", _id: "5c607cfec27d6254c6fe0ca1", projectName: "I LOVE THIS GAME", … } ]

parentComponent.js

async componentDidMount() {
  this._isMounted = true
  let response = await fetch(`http://localhost:5001/userproject/${taskId}`)
  let data = await response.json()
  console.log(data) // will show me the array
  const projects = data.map(pro => {
    return {
      id: pro._id,
      state: pro.state,
      projectName: pro.projectName,
      consultants: pro.consultants,
      ScrumMasterUsername: pro.scrumMaster.username,
      ScrumMasterId: pro.scrumMaster._id,
    }
  })
  return this.setState({
    projects: { projects },
  })
}

render() {
  const { projects } = this.state

  const list = (projects && projects.projects) || []
  if (!projects) {
    return null
  }
  return (
    <div className="dashboard container">
      <div className="row">
        <div className="col s16 m7  darken-2">
          <ProjectList
            name={this.state.projects.projectName}
            projects={list}
          />
        </div>
        <div className="col s12 m3 offset-m1">
          <Notifications />
        </div>
      </div>
    </div>
  )
}

我的问题:尝试获取任务详细信息时,它将检索此任务的ID,而不是其他详细信息:

import React from 'react'

const ProjectDetails = props => {
  const id = props.match.params.id

  console.log(props) // i can only get the id
  return (
    <div className="container section project-details">
      <div className="card z-depth-0">
        <div className="card-content">
          <span className="card-title">Project Title - {id} </span>
        </div>
      </div>
    </div>
  )
}
export default ProjectDetails

1 个答案:

答案 0 :(得分:0)

这就是您应该这样做的方式。

class App extends React.Component {
    render() {
        return (
            <Router>
                <div>
                    <Switch>
                        <Route path="/" component={Home} />
                        **<Route path="/about" render={(props) => <About {...props} isAuth={"Authenticated"} />} />**
                        <Route path="/topics" component={Topics} />
                    </Switch>
                </div>
            </Router>
        );
    }
}

标记为星星之间的第二条路线是我渲染组件并传递道具isAuth={"Authenticated"}的路线 以上道具将在About组件中以

形式提供
const About = (props) => {
    return (
        <div>
            <h1>About={props.isAuth}</h1>
        </div>
    );
}

希望这对您有帮助!