简体   繁体   English

每次渲染组件时刷新组件状态

[英]refresh component state every time it is rendered react

I have an API running and I am trying to fetch that to get some information about some products. 我正在运行一个API,我正在尝试获取该API以获取有关某些产品的一些信息。 I am using react router to route the products and using that to fetch the API. 我正在使用React Router路由产品,并使用它来获取API。 However, when I try clicking on a different product the information from the previous product remains no matter what I do. 但是,当我尝试单击其他产品时,无论我做什么,都将保留先前产品的信息。

Here is my fetch: 这是我的提取物:

componentWillMount(){
let id = this.props.params.id + 3;
let url = 'http://localhost:8000/api/item/' + id + '/';
return fetch(url)
  .then(results => results.json())
  .then(results => this.setState({'items': results}))
  .catch(() => console.log(this.state.items));

and where I call the fill the information 以及我在哪里填写信息

render() {
return (
  <div className="itemPageWrapper">
    <div className="itemImgWrapper" />
    <div className="itemInfoWrapper">
      <Link className="backLink" to="/">
        <span className="small">
          <svg fill="#000000" height="13" viewBox="0 0 18 15" width="13" xmlns="http://www.w3.org/2000/svg">
            <path d="M7 10l5 5 5-5z"/>
            <path d="M0 0h24v24H0z" fill="none"/>
          </svg>
        </span>All Items
      </Link>
      <h3 className="itemName">{this.state.items[Number(this.state.id)].name}</h3>
      <p className="itemCost frm">{this.state.items[Number(this.state.id)].price}</p>
      <p className="description">
        {this.state.items[Number(this.state.id)].description}
      </p>
      <p className="seller frm">By <span>{this.state.items[Number(this.state.id)].brand}</span></p>
    <button className="reqTradeBtn normalBtn">Order</button>
    </div>
  </div>

I receive an error saying TypeError: Cannot read property 'name' of undefined if I change anything. 我收到一条错误消息,提示TypeError:如果我进行任何更改,则无法读取未定义的属性“名称”。 I am using a +2 because my API starts at 3. How would I make this work for all products 我使用的是+2,因为我的API从3开始。我如何在所有产品上使用该功能

You should check if you had that items loaded 您应该检查是否已加载了这些物品

this.state.items[Number(this.state.id)] this.state.items [号码(this.state.id)]

render() {
   const item = this.state.items[Number(this.state.id)];

   if (!item) {
      return 'Loading';
   }

   return (
       <div className="itemPageWrapper">
       ......
       </div>
   );
}

Also you rewrite state.items each time. 另外,您每次都重写state.items。 Maybe you should use some Redux to store this collection globally. 也许您应该使用Redux在全球存储此集合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM