我正在使用 React JS 创建一个网站,以允许用户点击一个品牌并从 Instagram 抓取图片。在着陆页 /landing 上,用户可以选择一个品牌,并将该品牌名称传递到 Instagram 抓取页面 /instagramScraper:
this.props.history.push({
pathname: '/instagramScraper',
params: {
brandName: this.state.brand_name
}
});
instagram scraper 页面使用以下代码获取 brandName:
this.state.brandName = props.location.params["brandName"];
用户现在可以点击此 /instagramScraper 上的图片,然后被带到另一个可以编辑图片的页面 /editPhoto。从 /editPhoto 选择“后退按钮”后,出现此错误:
TypeError: Cannot read property 'brandName' of undefined new Landing
src/components/instagramScraper.js:24
21 | this.onAddImages = this.onAddImages.bind(this);
22 | this.onScrape = this.onScrape.bind(this);
23 | this.learnMore = this.learnMore.bind(this);
> 24 | this.state.brandName = props.location.params["brandName"];
当从 photoEdit 页面选择后退按钮时,如何传递 brandName 参数?我曾尝试在着陆页中使用 this.setState,但 brandName 的值被重置。
最佳答案
因此,由于您将其作为参数传递,因此当您返回时,该参数将丢失。除了参数,您还可以使用查询字符串或部分 url 路径吗?例如。 /landing/instagramScraper/brandName
或 /landing/instagramScraper?brandName=NAME
。这将帮助您将信息保存在位置历史记录中,然后后台将正常工作。另一种选择是使用 react-router,它有助于在 React SPA 上进行路由,并且会处理状态。
关于javascript - react JS : Passing values when back button is clicked,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49139132/