Reactjs 通过react路由器链路组件发送道具
我在通过react路由器的链接组件发送道具时遇到问题。 这是我的组件,负责显示特定元素:Reactjs 通过react路由器链路组件发送道具,reactjs,react-router,Reactjs,React Router,我在通过react路由器的链接组件发送道具时遇到问题。 这是我的组件,负责显示特定元素: const ItemRecipe = ({ recipe }) => { const { label, image } = recipe.recipe; return ( <li> <p> {label} </p> <img src={image} alt="food" /> <Link to
const ItemRecipe = ({ recipe }) => {
const { label, image } = recipe.recipe;
return (
<li>
<p> {label} </p>
<img src={image} alt="food" />
<Link to={{pathname: `/meals/${label}`, params: recipe }}>
<p>next</p>
</Link >
</li>
);
}
const ItemRecipe=({recipe})=>{
const{label,image}=recipe.recipe;
返回(
{label}
下一个
);
}
点击后,我想打开一个特定的食谱页面。这个组件看起来像这样
class DetailsRecipe extends Component {
constructor(props) {
super(props);
this.state = {
recipe: props.match.params.recipe
}
console.log(this.state.recipe);
}
render () {
<div>
lorem lorem
</div>
)
}
}
类详细信息CIPE扩展组件{
建造师(道具){
超级(道具);
此.state={
配方:props.match.params.recipe
}
console.log(this.state.recipe);
}
渲染(){
洛雷姆·洛雷姆
)
}
}
console.log(this.state.recipe)
显示undefined
。
如何修复此错误?如何通过react路由器的链路组件正确发送数据
我在stackoverflow上查看了类似的主题,但这无助于解决我的问题再看看链接组件的功能。to
对象中允许的属性包括:
- pathname:表示要链接到的路径的字符串
- 搜索:查询参数的字符串表示形式
- 散列:放在URL中的散列,例如#A-hash
- 状态:保存到该位置的状态
state
而不是params
编辑:
因此,您的代码如下所示:
<Link to={{pathname: `/meals/${label}`, state: {"recipe": recipe} }}>
this.state = {
recipe: props.location.state.recipe
};
我把props.match.params.recipe改为props.match.params,这没关系,但我只传递了名称,没有传递整个配方对象。我真的不明白你改变了什么。你试过我的建议了吗?我改变了这个.state={recipe:props.match.params},它还可以。但这不是我的目标,我想通过react routerSee中的链接传递对象查看我的更新答案以了解状态使用的示例。您是否使用类似于向路由组件注入道具的方法?这也许可以解释为什么
props.match
可以,但是props.location
不行。