import ReactDOM from 'react-dom'
import React from 'react'
class Loading extends React.Component {
render () {
return (
<div>加载中....</div>
)
}
}
const node = null
const loading = {
show () {
const node = document.createElement('div')
document.body.appendChild(node)
ReactDOM.render(<Loading />, node)
},
hide () {
if (!node) return
ReactDOM.unmontComponentAtNode(node)
document.body.removeChild(node)
}
}
export default loading
可以下面的组件内部合适的地方调用loading.show()和loading.hide()方法。数据加载的过程中会调用loading.show()。数据加载完毕调用loading.hide()。
import React from 'react'
import './index.scss'
import { PropTypes } from 'mobx-react'
import loading from '../../../publicComponents/Loading/index'
class User1 extends React.Component {
componentDidMount () {
loading.show()
}
componentWillUpdate () {
console.log('User1 Upate')
}
render () {
console.log('User1 render')
return (
<div>{this.props.Time}{this.context.color}</div>
)
}
}
User1.contextTypes = {
color: PropTypes.string
}
export default User1
或者说,index.js页面可以这样写
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './vdom/index5';
import * as serviceWorker from './serviceWorker';
class Init extends React.Component {
render () {
return (
<div>加载中....</div>
)
}
getData() {
return new Promise((resolve) => {
setTimeout(() => {
resolve(1)
}, 1000)
})
}
async componentDidMount() {
const data = await this.getData()
ReactDOM.unmountComponentAtNode(document.getElementById('root'))
ReactDOM.render(<App />, document.getElementById('root'));
}
}
ReactDOM.render(<Init />, document.getElementById('root'));
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
也可以用继承的方式来写
import ReactDOM from 'react-dom';
import React from 'react'
class Loading extends React.Component {
constructor(props) {
super(props)
this.state = {
isShow: false
}
}
render() {
const { isShow } = this.state
return (
<div>{isShow ? "加载中..." : ''}</div>
)
}
show() {
this.setState({
isShow: true
})
}
hide() {
this.setState({
isShow: false
})
}
}
class App extends Loading {
constructor(props) {
super(props)
this.state = {
name: '你好',
friend: {
name: '早上好'
},
animal: 'dog'
}
}
componentDidMount () {
this.show()
setTimeout(() => {
this.hide()
},3000)
}
componentWillUpdate () {
}
render () {
return (
<div>
{super.render()}
hello
</div>
)
}
}
export default App