尝试在我的React.js项目中创建加载图标(应用程序在React中构建,从Wordpress REST API获取数据并使用Flux处理状态)。但是componentDidMount()永远不会被触发,所以我的加载图标永远不会消失..这是我的app.js:
class App extends Component {
templates = {
'about': About,
'contact': Contact,
'archive': Archive
}
buildRoutes(data){
return data.pages.map((page, i) => {
return(
<Route
key={i}
component={this.templates[page.slug]}
path={`/${page.slug}`}
exact
/>
)
})
}
run(){
DataActions.getPages((response) => {
render(
<div>
<div className="loaderSmall" id="loaderSmall">
<div className="pixel-loader"></div>
</div>
<Router>
<div>
<Header />
<Switch>
<Route path="/" component={Home} exact />
{this.buildRoutes(response)}
<Route render={() => { return <Redirect to="/" />}} />
</Switch>
<Footer />
</div>
</Router>
</div> , document.getElementById('app')
);
});
}
componentDidMount() {
window.addEventListener('load', this.handleLoad);
console.log("componentDidMount");
}
// Fade out site-loader
handleLoad() {
console.log("CALLED");
var fadeTarget = document.getElementById("loaderSmall");
var fadeEffect = setInterval(function () {
if (!fadeTarget.style.opacity) {
fadeTarget.style.opacity = 1;
}
if (fadeTarget.style.opacity < 0.1) {
clearInterval(fadeEffect);
} else {
fadeTarget.style.opacity -= 0.1;
}
}, 1000);
}
}
..我没有错误:
答案 0 :(得分:0)
你的代码在开始时看起来很好,但是当我仔细观察时,我可以看到它
您的代码缺少render()
方法。我添加了一个“存根”渲染,它有效。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://unpkg.com/react@15/dist/react.min.js"></script>
<script src="https://unpkg.com/react-dom@15/dist/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.24.0/babel.js"></script>
</head>
<body>
<div id="app"></div>
<img id="loaderSmall" src="https://www.w3schools.com/images/w3schools_green.jpg" alt="W3Schools.com">
<script type="text/babel">
class App extends React.Component {
// When Component has rendered, window.addEventListener adds event "load" and calls handleLoad function
componentDidMount() {
window.addEventListener('load', this.handleLoad);
}
// Fade out site-loader
handleLoad() {
var fadeTarget = document.getElementById("loaderSmall");
console.log(fadeTarget);
var fadeEffect = setInterval(function () {
if (!fadeTarget.style.opacity) {
fadeTarget.style.opacity = 1;
}
if (fadeTarget.style.opacity < 0.1) {
clearInterval(fadeEffect);
} else {
fadeTarget.style.opacity -= 0.1;
}
}, 300);
}
render(){return <div></div>} // This was missing
}
ReactDOM.render(
<App/>,
document.getElementById("app")
)
</script>
</body>
</html>