我是 React JS 的新手,现在对组件生命周期方法的工作方式感到困惑;在我的例子中,这与 ReactJS.org 文档完全矛盾。预期的行为是,componentDidMount() 应该在 render() 之前执行,但是 render() 在 componentDidMount() 之前执行。
我的源代码:
import React from 'react';
import '../main.css';
//import sam from "../images/gallery/Farmer1.jpg";
import galleries from './GalleryImages.js';
class Gallery extends React.Component {
constructor(props) {
super(props);
}
cache = {};
dummy = './Farmer1.jpg';
importAll = (r, ping) => {
console.log(ping + ' called');
r.keys().forEach(key => {
this.cache[key] = r(key);
console.log(`key is ${key} and value : ${r(key)}`);
this.dummy = r(key);
});
console.log(this.cache);
};
componentDidMount() {
this.importAll(
require.context('../images/gallery/', false, /\.jpg$/),
'mount'
);
}
render() {
//this.importAll(require.context('../images/gallery/', false, /\.jpg$/),"render");
console.log(this.cache);
const gallery = galleries.map(gallery => {
return (
<a
className="spotlight"
href={gallery.src}
data-title={gallery.title}
data-description={gallery.description}
>
{console.log(this.cache[gallery.src])}
<img src={this.cache[gallery.src]} />
</a>
);
});
return (
<div className="container margintop150">
<div className="greentext center">
<h4>
{' '}
<b>Gallery</b>
</h4>
</div>
<h5 className="type_5" />
<div className="row">
<div
className="spotlight-group"
data-title="Untitled"
data-animation="fade"
data-fullscreen="false"
data-maximize="false"
data-minimize="false"
>
{gallery}
</div>
</div>
</div>
);
}
}
export default Gallery;
//GalleryImages.js
const galleries = [
{
src: './Farmer2.jpg',
title: 'Farmer2',
description: 'farmer2'
},
{
src: './Farmer1.jpg',
title: 'Farmer1',
description: 'farmer1'
},
{
src: './Farmer3.jpg',
title: 'Farmer3',
description: 'farmer3'
}
];
export default galleries;
如果在 componentDidMount()
中调用 this.importAll()
,则类变量 this.cache 为 null
,但它会占用如果在 render()
中调用 this.importAll()
的值。
最佳答案
这是正确的行为,在渲染后调用 componentDidMount()。
These methods are called in the following order when an instance of a component is being created and inserted into the DOM:
* constructor()
* static getDerivedStateFromProps()
* render()
* componentDidMount()
之前调用了已弃用的 componentWillMount()。
Note: These methods are considered legacy and you should avoid them in new code:
UNSAFE_componentWillMount()
关于javascript - 渲染后调用react componentDidMount执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58043523/