reactjs - 通过 react-router Link 组件发送 props
问题描述
我在通过 react-router 的 Link 组件发送道具时遇到问题。这是我负责显示特定元素的组件:
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>
);
}
单击后,我想打开带有特定食谱的页面。这个组件看起来像这样
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>
)
}
}
console.log(this.state.recipe)
显示undefined
. 如何解决此错误?如何通过 react-router 的 Link 组件正确发送数据?
我在stackoverflow上查看了类似的主题,但它无助于解决我的问题
解决方案
再看一下 Link 组件的文档。对象内部允许的to
属性是:
- 路径名:表示要链接到的路径的字符串。
- search:查询参数的字符串表示。
- 散列:要放入 URL 的散列,例如 #a-hash。
- state:要持续到该位置的状态。
我猜你想使用state
而不是params
.
编辑:
所以你的代码看起来像这样:
<Link to={{pathname: `/meals/${label}`, state: {"recipe": recipe} }}>
然后您可以state
像这样访问链接组件的内部:
this.state = {
recipe: props.location.state.recipe
};
推荐阅读
- javascript - 离子页面数据不更新
- google-apps-script - 为什么 ClockTriggerBuilder 的 after() 方法运行不正确?
- javascript - ReactJs 中如何提供存储增强器的输入
- c# - AutoMapper 9.x 如何更新现有实体对象
- swift - 如何制作方形视频?
- c# - 从 Azure 云中 Windows Server 上运行的 Active Directory 获取用户
- javascript - 将几天的数组拆分为几个月
- javascript - Return observable from async function
- javascript - 如何更新在 JSX.Element 中创建的组件?
- python - 使用 pip 7.1.2 和 Python 3.5 完全无法安装任何包