2021年5月4日星期二

this.setState not updating value for render [duplicate]

I have a class with a constructor:

constructor(props) {          super(props);          this.state = {                image: null,                imageArray: []          };          const tempImageArray = [];          storage.ref("images").listAll().then((res) => {          res.items.forEach(img => {          img.getDownloadURL().then((url) => {            tempImageArray.push({              id: this.state.imageArray.length,              name: url            });          });        });      });          this.setState({ imageArray: tempImageArray });          console.log(tempImageArray);  

at this point the tempImageArray contains the stuff that I want

Then in my render function:

render () {      console.log(this.state.imageArray);      return (        <div className="App">          <header className="App-header">            <DisplayImg images = {this.state.imageArray} />            <input              type="file"              onChange={newImageHandler}            />            <button onClick={fileUploadHandler}>Upload</button>            </header>        </div>      );    }  

the this.state.imageArray is still empty. I thought that after going from constructor to render it would complete one cycle so the this.state.imageArray would've updated and have the new values. Does anyone know how I could get it to update the values for imageArray so I can call DisplayImg with the new values.

https://stackoverflow.com/questions/67394251/this-setstate-not-updating-value-for-render May 05, 2021 at 10:02AM

没有评论:

发表评论