如何从React Router路径获取URL参数

时间:2017-08-22 04:27:30

标签: reactjs express react-router

我正在MERN(Mongo,Express,React和Node)堆栈上创建一个简单的CRUD配方应用程序,在我构建了所有其他有点痛苦的逻辑之后,我犯了改装React路由器的错误。 / p>

我似乎无法从路线

访问我个人食谱的参数

students.add((Student)s);

以下是路线中引用的配方组件:

<Route exact path='/recipe/:recipeId' render={() => (<Recipe getRecipe={this.props.getRecipe} edit={this.props.updateRecipe} />)} />

我尝试过几种不同的方式调用import React from 'react'; import moment from 'moment'; import IngredientsList from './ingredients-list.js'; export default class Recipe extends React.Component { constructor(props) { super(props); console.dir(this.props); let id = this.props.match.params.recipeId; this.setState({ recipe: this.props.getRecipe(id), }); }; componentDidMount = () => { console.dir(this.props); let id = this.props.match.params.recipeId; this.setState({ recipe: this.props.getRecipe(id), }); } render() { return ( <div className="recipe-display container-fluid"> <div className="recipe-header"> <h1>{this.state.recipe.name}</h1> <h3>By {this.state.recipe.author}</h3> <hr /> <h4>Category: {this.state.recipe.category}</h4> <p className="recipe-date">Created: {moment(this.state.recipe.createdDate).format('MMMM Do YYYY, h:mm a')}</p> <p>Description: {this.state.recipe.description}</p> <div className="recipe-btns"> <button className="btn btn-danger pull-right btn-sm close-recipe" onClick={this.props.close} title="Close this Recipe">Close</button> <button className="btn btn-success pull-right btn-sm edit-recipe" onClick={this.props.edit} title="Edit this Recipe">Edit</button> </div> </div> <div className="recipe-body"> <div className="recipe-timing"> <p>Prep Time: {this.state.recipe.prepTime}</p> <p>Cook Time: {this.state.recipe.cookTime}</p> </div> <div className='ingredients panel panel-info'> <div className='panel-heading'>Ingredients:</div> <div className='panel-body'> <div className="ingredients-list"> <IngredientsList ingredients={this.state.recipe.ingredients} /> </div> </div> </div> <div className='directions panel panel-success'> <div className='panel-heading'>Directions:</div> <div className='panel-body'> {this.state.recipe.directions} </div> </div> </div> </div> ); } } ,在各种生命周期函数的构造函数中等等。我目前得到的错误是

this.props.match.params.recipeId

我可能错过了一些简单的事情。谢谢!

1 个答案:

答案 0 :(得分:0)

试试这个:

<Route exact path='/recipe/:recipeId' render={(props) => (<Recipe getRecipe={this.props.getRecipe} edit={this.props.updateRecipe} {...props} />)} />

原始代码的问题是,您没有将道具发送到<Recipe />。如果您使用render,则必须手动发送道具。

相关问题