无法将道具映射到我的 React Router 的 Link 组件

Can't map props passed to my React Router's Link component

我正在从我的 parent 传递道具,如下所示:

{Object.keys(this.state.recipes).map(key => {
  return (
    <Link
      key={key}
      to={{
        pathname: `/view/${key}`,
        state: {
          recipe: this.state.recipes[key]
        }
      }}
    >
      <Recipe
        key={key}
        index={key}
        recipe={this.state.recipes[key]}
        deleteRecipe={this.deleteRecipe}
        editRecipe={this.editRecipe}
      />
    </Link>
  );
})}

这是我的路由器的样子:

<BrowserRouter>
  <div>
    <Route exact path="/" component={App} />
    <Route path="/view/:recipeId" component={ViewRecipe} />
  </div>
</BrowserRouter>

我正在尝试从这个组件访问该道具

ViewRecipe.js

class ViewRecipe extends React.Component {
  constructor(props) {
    super(props);
    this.state = { recipe: {} }
  }

  componentDidMount() {
    const { recipe } = this.props.location.state;
    this.setState({ recipe: recipe });
  }

  render() {
    return (
      <div>
       <h1>{this.state.recipe.recipeName}</h1>
    <img src={this.state.recipe.dishImg} alt="Dish" />
        <ul>
           {this.state.recipe.ingredients.map( ingredient => <li>{ingredient}</li>)}
        </ul>
        <ul>
          <li>direction</li>
          <li>direction</li>
          <li>direction</li>
          <li>direction</li>
          <li>directio</li>
        </ul>
      </div>
    );
  }
}

我的ViewRecipe.js状态是这样的:

recipeName 和 dishImg 正确呈现,但是当我尝试映射我的成分时,出现以下错误

这可能是未定义的

    <ul>
       {this.state.recipe.ingredients.map( ingredient => <li>{ingredient}</li>)}
    </ul>

为此你必须像这样修改代码才能工作

    <ul>
       {this.state.recipe && this.state.recipe.ingredients && this.state.recipe.ingredients.map( ingredient => <li>{ingredient}</li>)}
    </ul>

上面我们正在检查是否在做地图之前定义了所有内容希望这会起作用

编辑:

您不能对非数组使用 .map 函数。 null.map 结果未定义 :)