Javascript React JS:单击后退按钮时传递值
我正在使用React JS创建一个网站,允许用户点击某个品牌并从Instagram中抓取图像。在登录页面/landing,用户可以选择一个品牌,该品牌名称将传递到Instagram scraper页面/instagramScraper:Javascript React JS:单击后退按钮时传递值,javascript,reactjs,react-props,Javascript,Reactjs,React Props,我正在使用React JS创建一个网站,允许用户点击某个品牌并从Instagram中抓取图像。在登录页面/landing,用户可以选择一个品牌,该品牌名称将传递到Instagram scraper页面/instagramScraper: this.props.history.push({ pathname: '/instagramScraper', params: { brandName: this.state.brand_name }
this.props.history.push({
pathname: '/instagramScraper',
params: {
brandName: this.state.brand_name
}
});
instagram scraper页面使用以下代码获取品牌名称:
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,但是品牌名的值被重置。您需要使用
this.state = {
brandName: ...
}
而不是构造函数中的
this.state.brandName=…
,因此,由于您将其作为参数传递,当返回时,该参数将丢失。除了参数之外,您还可以使用查询字符串或url路径的一部分吗?例如/landing/instagramScraper/brandName
或/landing/instagramScraper?brandName=NAME
。这将有助于您在位置历史记录中保存信息,然后备份将起作用。另一种选择是使用react router,它有助于在react SPA上进行路由,并会处理状态。在单击返回时看起来是这样的,而不是像/instagramScraper/brandName
那样的URL,它看起来像/instagramScraper
。这是正确的吗?@Rush在复制代码时,我完全错了。单击/landing/instagramScraper/editPhoto上的“上一步”时,它会查看/landing/instagramScraper',但是/landing/instagramScraper中由/landing传入的brandName参数是未定义的。如果您使用路由包,例如react router
,则当前未定义。那是我需要用的东西吗?好的,我知道了。因此,由于您将其作为参数传递,当您返回时,该参数将丢失。除了参数之外,您还可以使用查询字符串或url路径的一部分吗?例如/landing/instagramScraper/brandName
或/landing/instagramScraper?brandName=NAME
。这将帮助您在位置历史记录中保存信息,然后返回
将起作用。另一种选择是使用react router
,这有助于在react SPA上进行路由,它将处理状态。感谢您的回复。但是,当我在构造函数中使用以下内容时,仍然会遇到相同的错误:this.state={brandName:props.location.params[“brandName”]}