首页 > 解决方案 > 为什么道具传递到另一个页面时为空 - React?

问题描述

我正在尝试找到一种方法来从Card.js(嵌套在Home.js)传递一个 id。这个想法是,当用户点击卡片时,将获取 id 属性并将其作为变量传递到RecipeDetails.js页面,并且配方详细信息将显示在此页面上。我成功地将 id传递给了,App.js但是当它传递给 时RecipeDetails.jsprops.id 始终为空。我进行了研究,看到人们使用 useHistory,但不确定如何在我的案例中实现它。任何帮助,将不胜感激。提前致谢!

这是我的应用程序结构:
App.js
---- Home.js
      ---- StaffPicks.js
            ---- <Card id={item.id}/>
----RecipeDetails.js

详细来说,App.js 我有 2 个页面,如下所示:

function App(){
const [id, setId] = useState("");
useEffect(() => {}, [id]);
  return(
    <Switch>
      <Route
          path="/"
          exact
          component={() => (<Home/>)}
       />
       <Route
          path="/RecipeDetails"
          exact
          component={() => <RecipeDetails id={id}/>}
       />
    </Switch>
  )
}

Card.js零件:

const MiniDishCard = (props) => {
  const [cardId, setCardId] = useState("");

  useEffect(() => {
    // console.log(cardId);
    props.setId(cardId);
  }, [cardId]);

  return (
    <Gallery>
      {props.data.map((item, index) => {
        return (
          <Card
            key={index}
            id={item.id}
            onClick={(e) => {
              setCardId(e.currentTarget.id);
            }}
          >
            <Link className="link" to="/RecipeDetails" target="_blank">
              <ImageWrapper>
                <img src={item.image} alt="Recipe Picture" />
              </ImageWrapper>
              <TextWrapper>
                <h3>{item.title}</h3>
                <IngredientsWrapper>
                  {item.missedIngredients.map((ingredient, index) => {
                    return <p key={index}>{ingredient.name}</p>;
                  })}
                  {item.usedIngredients.map((ingredient, index) => {
                    return (
                      <b key={index}>
                        <p>{ingredient.name}</p>
                      </b>
                    );
                  })}
                </IngredientsWrapper>
              </TextWrapper>
            </Link>
          </Card>
        );
      })}
    </Gallery>
  );
};

export default MiniDishCard;

RecipeDetails.js零件:

const DetailedRecipe = (props) => {
  const id = props.id;
  //console.log(id) always returns empty objects
  console.log(id)
  const info = {
    apiURL: `https://api.spoonacular.com/recipes/{id}/information`,
    apiKey: "***",
    apiURL2: `https://api.spoonacular.com/recipes/${id}/analyzedInstructions`,
  };
  
  const {
    data: recipe,
    error: recipeError,
    isLoading: recipeIsLoading,
  } = useFetch(`${info.apiURL}?apiKey=${info.apiKey}`);

  

  

  return ();
};

标签: reactjsreact-hooks

解决方案


一些上下文怎么样?https://reactjs.org/docs/hooks-reference.html#usecontext

export const AppContext = React.createContext(null)

function App() {
const [id, setId] = useState("");

return (
    <AppContext.Provider value={{ id, setId }}>
        <Switch>
            <Route
                path="/"
                exact
                component={() => (<Home/>)}
            />
            <Route
                path="/RecipeDetails"
                exact
                component={() => <RecipeDetails />}
            />
        </Switch>
    </AppContext.Provider>
  )
}

RecipeDetails.js和中Card.js

import { useContext } from 'react'
import { AppContext } from './App'

// Use inside components
const { id, setId } = useContext(AppContext)

推荐阅读