reactjs - 为什么道具传递到另一个页面时为空 - React?
问题描述
我正在尝试找到一种方法来从Card.js
(嵌套在Home.js
)传递一个 id。这个想法是,当用户点击卡片时,将获取 id 属性并将其作为变量传递到RecipeDetails.js
页面,并且配方详细信息将显示在此页面上。我成功地将 id传递给了,App.js
但是当它传递给 时RecipeDetails.js
,props.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 ();
};
解决方案
一些上下文怎么样?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)
推荐阅读
- go - 寻找有损/无损 VP8X 比特流
- adapter - 如何在另一个 RecyclerView 的嵌套 RecyclerView 中显示可变数量的项目?
- java - 如何将一个整数的三位数字相加?
- database - 查询表达式 strUserPassword 中的语法错误
- javascript - Discord,js TypeError:member.guild.roles.find 不是函数
- php - Symfony,当我在主机 1and1 上将网站投入生产时出现错误 500
- tensorflow - Keras 和 tensorflow:复杂自定义损失函数的梯度
- post - Odoo 中的 GET/POST 请求到外部 API
- c# - 在c#中获取用户输入并保存在数组中的问题
- docker - 将 Go 服务器作为 Docker 容器运行时出现权限被拒绝错误