React JS:单击后退按钮时传递值

React JS: Passing values when back button is clicked

我正在使用 React JS 创建一个网站,以允许用户点击品牌并从 Instagram 抓取图片。在着陆页 /landing 上,用户可以 select 一个品牌,这个品牌名称会传递到 Instagram 抓取页面 /instagramScraper :

    this.props.history.push({
      pathname: '/instagramScraper',
      params: {
        brandName: this.state.brand_name
      }
    });

instagram 抓取页面使用以下代码获取品牌名称:

this.state.brandName = props.location.params["brandName"];

用户现在可以点击此 /instagramScraper 上的图片,然后被带到另一个页面 /editPhoto可以编辑。在 select 从 /editPhoto 编辑 "back button" 后,我得到这个错误:

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 页面 select 编辑后退按钮时,如何传递 brandName 参数?我尝试在着陆页中使用 this.setState,但是品牌名称的值被重置了。

你需要使用

this.state = {
  brandName: ...
}

而不是 this.state.brandName = ... 在你的构造函数中

因此,由于您将其作为参数传递,因此当您返回时,该参数将丢失。除了参数,您还可以使用查询字符串或 url 路径的一部分吗?例如。 /landing/instagramScraper/brandName/landing/instagramScraper?brandName=NAME。这将帮助您将信息保存在位置历史记录中,然后后台将正常工作。另一种选择是使用 react-router,它有助于在 React SPA 上进行路由,并且会处理状态。