简体   繁体   中英

Reload a part of page using React

Does anyone have any idea how can I reload a specific part of a page when pressing a customized refresh button in React?

Can anyone also give an example?

Thanks!

My code:

constructor(props) {
 super(props);
 this.state = {
  products: this.props.productData //where productData an array of all products-ID
 };
 this.refresh = this.refresh.bind(this);
}

refresh() {
  this.setState({ products: null });
  this.forceUpdate();
}

render() {
  const { products } = this.state;
        <Button onClick={this.refresh} />
        <ListComponent
          data={products.map(entry => ({
            text: entry.productId
          }))}
        />
  );
}

I don't know if this is actually how you are supposed to do it, but here is a hack that I use,

Put the div in a property in the state(let's call it element ). Then, when you are calling refreshFunction () , change what's in this.state.element with an empty div (or a custom made div that should show while you fetch the new data). After you've fetched the new data, put it back in this.state.element , and update any other property that you need.

  1. Your products variable is not referencing any property from the state. Just call it directly in the JSX as Adrian mentioned.

  2. You need to wrap your JSX within a common div.

  3. I am assuming your button is not a component hence the change below. (If it is a component, then please post that component as well in your question and I'll update this answer accordingly).

  4. Your render is not returning anything as it is. You need to your render to return your content.


Change the render section of your code to the following and let me know what you see in the console:

render() {
    return ( 
        <div>
            <button onClick={this.refresh}>Refresh</button>
            <ListComponent
              data={this.state.products.map(entry => ({
                text: entry.productId
              }))}
            />
        </div>
    )
}

If the problem still persists, please post the <ListComponent/> part of the code as well as the complete code of the above component in your question too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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