简体   繁体   English

如何在 React 中通过 Link 传递道具(this.props.location 未定义)

[英]How to pass props via Link in React (this.props.location is undefined)

i am creating a recipe research project in react.我正在创建一个反应配方研究项目。 On the home page I press 'search recipe' and it finds them for me, then 'view recipe' and it should show me some data that I have to decide.在主页上,我按“搜索食谱”,它会为我找到它们,然后“查看食谱”,它应该会显示一些我必须决定的数据。 When in the component I go to do the console.log (this.props) it returns me all the object without the value of the state and therefore I cannot access the data.当在组件 I go 中执行 console.log (this.props) 时,它返回所有 object 没有 state 的值,因此我无法访问数据。 could you please help me?请你帮助我好吗? I leave you the code to understand better.我把代码留给你以便更好地理解。

import logo from "./logo.svg";
import "./App.css";
import React, { useState } from "react";
import MealList from "./MealList";

function App() {
  const [mealData, setMealData] = useState(null);
  /*const [calories, setCalories] = useState(2000)*/
  const [food, setFood] = useState("");

  function handleChange(e) {
    setFood(e.target.value);
  }

  function getMealData() {
    fetch(
      `https://api.spoonacular.com/recipes/complexSearch?apiKey=1d66c25bc4bb4ac288efecc0f2c4c4b8&diet=vegetarian` 
    ) /* &addRecipeInformation=true */
      .then((response) => response.json())
      .then((data) => {
        setMealData(data);
      })
      .catch(() => {
        console.log("error");
      });
  }

  return (
    <div className="App">
      <section className="controls">
        {/*<input type="number" placeholder='Calories (e.g. 2000)' onChange={handleChange}/>*/}
        <input type="string" placeholder="food" onChange={handleChange} />
      </section>
      <button onClick={getMealData}> CERCA PASTI VEGETARIANI</button>
      {mealData && <MealList mealData={mealData}/>}
    </div>
  );
}

export default App;


import React from "react";
import Meal from "./Meal";

export default function MealList({ mealData }) {

  return (
<main>
  <section className="meals">
    {mealData.results.map((meal) => {
      return <Meal key={meal.id} meal={meal} />;
    })}
  </section>
</main>

); ); } }

import React, {useState, useEffect} from 'react'
import {Link} from 'react-router-dom'

export default function Meal({meal}) {
    
    const [imageUrl, setImageUrl] = useState("");
    useEffect(()=>{
        fetch(`https://api.spoonacular.com/recipes/${meal.id}/information?apiKey=1d66c25bc4bb4ac288efecc0f2c4c4b8`)
        .then((response)=>response.json())
        .then((data)=>{
            setImageUrl(data.image)
        })
        .catch(()=>{
            console.log("errorn in meal js fetch")
        })
    }, [meal.id])

    const location = {
        pathname: '/somewhere',
        state: { fromDashboard: true }
      }
    return (
        <article>
            <h1>{meal.title}</h1>
            <img src={imageUrl } alt="recipe"></img>
            <div>
                <button className='recipeButtons'>
                    <Link to={{
                        pathname: `/recipe/${meal.id}`, 
                        state: {meal: meal.id}}}>
                        Guarda Ricetta
                    </Link>
                </button>
            </div>
        </article>
    )
}



import React from "react";

class Recipe extends React.Component{
   
    render() {
        console.log(this.props)
        return(
            <div>class Recipe extends React.Component</div>
        )
    }
}


export default Recipe;

this is the result of console.log(this.props) (this.props.location is undefined): this props这是 console.log(this.props) 的结果(this.props.location 未定义): this props

You haven't shown how you render <Recipe />, so I can't tell at a glance where the problem is.你还没有展示你是如何渲染 <Recipe /> 的,所以我不能一眼看出问题出在哪里。

However, you don't need to pass location as a prop.但是,您不需要将位置作为道具传递。 React-Router includes a hook, useLocation , which can be invoked from any function component. React-Router 包含一个钩子useLocation ,可以从任何 function 组件调用它。 You can change Recipe to a function component and use:您可以将配方更改为 function 组件并使用:

import { useLocation } from 'react-router-dom'

/* ... */

function Recipe(props) {
  const location = useLocation()
  /* ... */
}

ETA:预计到达时间:

Checking the type definitions for <Link/> and To , it appears the API reference on reactrouter.com is wrong.检查<Link/>To的类型定义,看来reactrouter.com 上的 API 参考是错误的。 To is, in fact, string | Partial<Path> To实际上是string | Partial<Path> string | Partial<Path> , where Path is: string | Partial<Path> ,其中Path是:

interface Path {
    /**
     * A URL pathname, beginning with a /.
     *
     * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.pathname
     */
    pathname: Pathname;
    /**
     * A URL search string, beginning with a ?.
     *
     * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.search
     */
    search: Search;
    /**
     * A URL fragment identifier, beginning with a #.
     *
     * @see https://github.com/remix-run/history/tree/main/docs/api-reference.md#location.hash
     */
    hash: Hash;
}

This is why the state is never being set.这就是为什么从未设置 state 的原因。 To set the state in the link, you need to include it as a React prop, like so:要在链接中设置 state,您需要将其作为 React 属性包含在内,如下所示:

<Link to={`/recipe/${meal.id}`} state={{ meal: meal.id }}>Guarda Ricetta</Link>

you can use functional component with react router hooks to access to the location instead of class component您可以使用带有反应路由器挂钩的功能组件来访问该位置,而不是 class 组件


import { useLocation } from "react-router-dom";

export default function Recipe () {
const location  = useLocation();

 return (
  <div> Recipe </div
 )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM